'use strict';
(function (exports) {
    /**
     * 胡牌类型（4003）
     * @tpye {Object}
     * */
    var majiang = {}
    majiang.HuType = {
        LiuJu: 0,          // 流局
        ZiMo: 1,           // 自摸
        DianPao: 2,        // 点炮
        WangDiao: 3,       // 王钓
        WangDiaoWang: 4,   // 王钓王
        WangChuang: 5,     // 王闯
        WangChuangWang: 6  // 王闯王
    };

    /**
     * 房间状态
     * @tpye {Object}
     * */
    majiang.RoomState = {
        NONE: 0,
        CREATED: 1,
        ONGOING: 2,
        ENDED: 3,
        JIESAN: 4,
        DELETIN: 5
    };

    /**
     * 可胡牌类型（4005）
     * @type {Object}
     * */
    majiang.Hu = {
        ZiMo: 0,           // 自摸
        WangDiao: 1,       // 王钓
        WangDiaoWang: 2,   // 王钓王
        WangChuang: 3,     // 王闯
        WangChuangWang: 4  // 王闯王
    };

    var signal1 = res.signal1;
    var signal2 = res.signal2;
    var signal3 = res.signal3;
    // var signal4 = cc.textureCache.addImage(res.signal1_4_png);
    // var signal5 = cc.textureCache.addImage(res.signal1_5_png);

    // var lb_gang = cc.textureCache.addImage(majiang_gs.res.lb_gang_png);
    // var lb_lai = cc.textureCache.addImage(majiang_gs.res.lb_lai_png);
    // var lb_pi = cc.textureCache.addImage(majiang_gs.res.lb_pi_png);
    // var lb_gui = cc.textureCache.addImage(majiang_gs.res.lb_gui_png);

    var ORIENTATION = {
        0: '东',
        1: '南',
        2: '西',
        3: '北'

    };
    var $ = null;

    var PAINAMES = ['', '一万', '二万', '三万', '四万', '五万', '六万', '七万', '八万', '九万', '一条', '二条', '三条', '四条', '五条', '六条', '七条', '八条', '九条', '一筒', '二筒', '三筒', '四筒', '五筒', '六筒', '七筒', '八筒', '九筒'];


    // CONST
    //发牌动画延时
    var FAPAI_ANIM_DELAY = 0.04;
    //发牌动画持续时间
    var FAPAI_ANIM_DURATION = 0.2;
    //摸牌动画持续时间
    var MOPAI_ANIM_DURATION = 0.3;
    var UPDOWNPAI_ANIM_DURATION = 0.088;
    //牌向上偏移距离（当单机牌时）
    var UPPAI_Y = 30;
    var CHUPAI_MID_NODE_SCALE_MAP = {0: 1.2, 2: 1.2, 1: 1.2, 3: 1.2};

    var MAP2PNUM = {1: 4, 2: 3};

    var OP_CHI = 1;
    var OP_PENG = 2;
    var OP_GANG = 3;
    var OP_HU = 4;
    var OP_PASS = 5;
    var OP_TING = 6;
    var OP_LIANG = 7;
    var OP_KAIGANG = 50;
    var OP_XIAOHU = 51;

    //创建
    var ROOM_STATE_CREATED = 1;
    //开始游戏
    var ROOM_STATE_ONGOING = 2;
    //结束游戏
    var ROOM_STATE_ENDED = 3;

    var posConf = {
        headPosBak: {}
        , paiA0PosBak: {}
        , paiA0ScaleBak: {}
        , paiADistance: []
        , paiALiangDistance: [0.5, 3.5, 0, -3.5]
        , paiMopaiDistance: {0: 16, 1: 40, 2: 20, 3: 40}
        , paiGDistance: []
        , paiUsedDistance: []
        , paiUsedZOrder: {
            0: {0: -1, 10: 0, 20: 1, 30: 2, 40: 3, 50: 4, 60: 5}
            , 1: {0: -1, 10: -1, 20: -1, 30: -1, 40: -1, 50: -1, 60: -1}
            , 2: {0: 0, 10: -1, 20: -2, 30: -3, 40: -4, 50: -5, 60: -6}
            , 3: {0: 0, 10: 1, 20: 2, 30: 3, 40: 4, 50: 5, 60: 6}
        }
        , cpghgPositionX: {
            2: [660, 920], 3: [425, 700, 960], 4: [320, 580, 840, 1070],
            5: [210, 460, 700, 940, 1130], 6: [210, 460, 700, 940, {x: 700, y: 360}, 1180]
        }
        , upPaiPositionY: null
        , downPaiPositionY: null
        , groupWidth: {}
        , groupHeight: {}
        , groupDistance: {0: 4, 1: 4, 2: 16, 3: 4}
        , groupToFirstPaiDistance: {0: 10, 1: -14, 2: 26, 3: -14}

        , paiPos: {}

        , ltqpPos: {}
        , ltqpRect: {}
        , ltqpCapInsets: {
            0: cc.rect(26, 31, 1, 1)
            , 1: cc.rect(26, 31, 1, 1)
            , 2: cc.rect(44, 25, 1, 1)
            , 3: cc.rect(42, 26, 1, 1)
        }
        , ltqpEmojiPos: {
            0: cc.p(40, 28)
            , 1: cc.p(39, 28)
            , 2: cc.p(40, 40)
            , 3: cc.p(56, 28)
        }
        , ltqpVoicePos: {
            0: cc.p(40, 28)
            , 1: cc.p(37, 28)
            , 2: cc.p(42, 40)
            , 3: cc.p(58, 28)
        }
        , ltqpEmojiSize: {}
        , ltqpTextDelta: {
            0: cc.p(0, -4)
            , 1: cc.p(-7, 2)
            , 2: cc.p(-1, 9)
            , 3: cc.p(8, 3)
        }
        , gPaiPos: {
            0: {1: 0, 2: 1, 3: 2},
            1: {0: 2, 2: 0, 3: 1},
            2: {0: 1, 3: 0, 1: 2},
            3: {0: 0, 1: 1, 2: 2}
        }
        //方向指标的角度
        , huFromAngle: [
            180,
            270,
            0,
            90
        ]
        //方向指标的位置
        , fromPos: [
            {x: 20, y: 80},
            {x: 50, y: 35},
            {x: 20, y: 20},
            {x: 20, y: 35}
        ]
    };

    var data;
    var isReconnect;

    var roomState = null;
    var mapId = 2;
    var playerNum = 4;
    var rowBegin = 1;

    var enableChupaiCnt = 0;

    var isCCSLoadFinished = false;

    var uid2position = {};
    var uid2playerInfo = {};
    var position2uid = {};
    var position2sex = {};
    var position2playerArrIdx = {};

    var hasChupai = false;

    var turnRow = null;

    var isReplay = null;

    var forRows = null;

    var baijiaoStep = 0;
    var baijiaoArr = [];
    var g_last_net_data = {};
    var g_ting_data = {};
    var g_krt_isting = {};

    var disabledChuPaiIdMap = {};

    var disableChupai = false;

    var curHuPaiId = 0;
    var playerHuPaiId = {};
    var zongjiesuanData = null
    var tiantingOpt = false;

    var clearVars = function () {
        roomState = null;
        mapId = gameData.mapId;

        playerNum = gameData.playerNum || MAP2PNUM[gameData.appId] || 4;
        rowBegin = 1;
        isCCSLoadFinished = false;
        uid2position = {};
        uid2playerInfo = {};
        position2uid = {};
        position2sex = {};
        position2playerArrIdx = {};
        hasChupai = false;
        turnRow = null;
        isReplay = null;
        forRows = null;

        disabledChuPaiIdMap = {};
        disableChupai = false;

        enableChupaiCnt = 0;
        zongjiesuanData = null;
    };

    var getPaiNameByRowAndId = function (row, id, isLittle, isStand) {

        var prefix;

        var ret = null;

        if (row == 0 && isLittle) prefix = 'p0s';
        if (row == 0 && !isLittle) prefix = 'p2l';
        if (row == 1 && isLittle) prefix = 'p1s';
        if (row == 1 && !isLittle) prefix = 'p2l';
        if (row == 2 && isLittle) prefix = 'p2s';
        if (row == 2 && !isLittle) prefix = 'p2l';
        if (row == 3 && isLittle) prefix = 'p3s';
        if (row == 3 && !isLittle) prefix = 'p2l';

        if (prefix) ret = prefix + id + '.png';

        if (row == 0 && id == 0 && isLittle) ret = 'p0s0' + '.png';
        if (row == 1 && id == 0 && isLittle) ret = 'p1s0' + '.png';
        if (row == 3 && id == 0 && isLittle) ret = 'p3s0' + '.png';
        if (row == 2 && id == 0 && !isLittle) ret = 'p2l0' + '.png';

        if (row == 0 && isStand && isLittle) ret = 'h0s' + '.png';
        if (row == 1 && isStand && isLittle) ret = 'h1s' + '.png';
        if (row == 3 && isStand && isLittle) ret = 'h3s' + '.png';
        if (row == 0 && isStand && !isLittle) ret = 'p2l0' + '.png';
        if (row == 1 && isStand && !isLittle) ret = 'by' + '.png';
        if (row == 3 && isStand && !isLittle) ret = 'bz' + '.png';
        // cc.log("getPaiNameByRowAndId ", row, id, isLittle, isStand, ret)
        return ret;
    };


    exports.MaLayer_lnbj = cc.Layer.extendEX({
        beforeOnCCSLoadFinish: null,
        afterGameStart: null,

        _clearView: function () {
            cc.log('_clearView');
            for (var i = 0; i < 4; i++) {
                safeHide($('info' + i + '.piao'));
                safeHide($('info' + i + '.offline'));
                safeHide($('info' + i + '.ok'));
                safeHide($('info' + i + '.ti'));
                safeHide($('info' + i + '.liang'));
                safeHide($('info' + i + '.zhuang'));
                safeHide($('info' + i + '.qp'));
                safeHide($('info' + i + '.btn_invite'));
                safeHide($('info' + i + '.btn_zhunbei'));
            }
            if (gameData.mapId == app.map_id.GanSu_KaErTiao) {
                $('cpghg.ting').setTexture(majiang_gs.res.btn_ting);
            }
        },
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);
            console.log('鹏涛重构过的服务器！');
        },

        onEnterTransitionDidFinish: function () {
            cc.Layer.prototype.onEnter.call(this);
            network.start();
        },

        /**
         * 显示测试
         * @private
         * */
        _showTest: function () {
            //showWindow('TestMahjong');
            this.addChild(new TestMahjong())
        },

        getRootNode: function () {
            return this.getChildByName('Scene');
        },
        initExtraMapData: function (data, is_Reconnect) {
            var that = this;
        },
        /**
         * 更换水印
         */
        showLogo: function () {
            var logNode = $('logo');
            logNode.setVisible(true);
        },
        addCustomListener: function (type, func) {
            this.addListener(type, func);
        },
        addListener: function (code, listener) {
            network.addListener(code, listener, this);
        },
        onCCSLoadFinish: function () {
            var that = this;

            addCachedCCSChildrenTo(majiang_gs.res.MaScene1_json, this);
            batchSetChildrenZorder(this.getRootNode(), {
                info0: 1,
                info1: 1,
                info2: 1,
                info3: 1,
                info_n0: 2,
                info_n1: 2,
                info_n2: 20,
                info_n3: 2,
                row2: 10,
                cpghg: 12,
                dingPanel: 100,
                btn_bg: 30,
                setting: 31,
                location_btn_red: 31,
                btn_changeTable: 31,
                chat: 29,
                jiesan: 31,
                btn_control_btns: 32,
                xuanpao_back: 100,
                btn_zhunbei: 999,
            });

            $ = create$(this.getRootNode());

            this.getPai = this.getPai();
            this.getGPai = this.getGPai();
            this.addUsedPai = this.addUsedPai();
            this.countDown = this.countDown();

            this.calcPosConf();
            this._clearView();
            MicLayer.init($('btn_mic'), this);

            if (isReconnect) {
                gameData.zhuangUid = data['zhuang_uid'];
                gameData.lianzhuang = data['lianzhuang'];
                gameData.leftRound = data['left_round'] || 0;
                gameData.totalRound = data['total_round'] || 8;
                gameData.curRound = data['cur_round'] || 0;

                gameData.players = data['players'];
                gameData.wanfaDesp = data['desp'];
                if (cc.isUndefined(gameData.wanfaDesp)) {
                    var options = data['options'];
                    gameData.wanfaDesp = options['desp'];
                }

                this._refreshRoundAndPai();
                this._refreshRoomState(data['room_status'] || majiang.RoomState.ONGOING);
                this.initExtraMapData(data, true);
            } else {
                this._refreshRoomState(majiang.RoomState.CREATED);
            }


            this.clearTable4StartGame(isReconnect, isReconnect, data);

            this.startTime();

            this.startSignal();

            safeHide($('btn_test'));

            //safeShow($('btn_test'));
            if (!cc.sys.isNative) {
                safeShow($('btn_test'));
                TouchUtil.setOnclickListener($('btn_test'), this._showTest.bind(this));
            }

            TouchUtil.setOnclickListener($('chat'), function () {
                showWindow('ChatWindow');
            });

            // TouchUtil.setOnclickListener($('Panel_1'), function () {
            //     that.hideControlBtns();
            // })

            TouchUtil.setOnclickListener($('setting'), function () {
                showWindow('SettingWindow', Setting_TYPE.Table_dou14);
            });
            TouchUtil.setOnclickListener($("location_btn_red"), function () {
                showWindow('PlayerInfoLocationWindow', false, that);
            });
            TouchUtil.setOnclickListener($('btn_changeTable'), function () {
                var curBackId = cc.sys.localStorage.getItem('newTableBackKEY') || 0;
                var _tempBg = null;
                if (parseInt(curBackId) < 5) {
                    _tempBg = res['table_back' + (parseInt(curBackId) + 1)];
                    $('bg').setTexture(_tempBg);
                    cc.sys.localStorage.setItem('newTableBackKEY', (parseInt(curBackId) + 1));
                } else {
                    $('bg').setTexture(res['table_back0']);
                    cc.sys.localStorage.setItem('newTableBackKEY', 0);
                }
            });
            TouchUtil.setOnclickListener($('btn_control_btns'), function () {
                that.changeBtnStatus();
            });
            TouchUtil.setOnclickListener($('btn_zhunbei'), function () {
                network.send(3004, {room_id: gameData.roomId});
            });

            TouchUtil.setOnclickListener($('btn_yxks'), function () {
                network.send(3004, {room_id: gameData.roomId});
            });


            TouchUtil.setOnclickListener($('btn_invite'), function () {
                ShareUtil.ShareRoomId(gameData.roomId, gameData.wanfaDesp, gameData.playerNum, gameData.players.length);
            });


            TouchUtil.setOnclickListener($('btn_fanhui'), function () {
                showMessageBox('确定要退出房间吗?', function () {
                    network.send(3003, {room_id: gameData.roomId});
                });
            });

            TouchUtil.setOnclickListener($('jiesan'), function () {
                if (that.getRoomState() == ROOM_STATE_CREATED) {
                    if (window.inReview)
                        network.send(3003, {room_id: gameData.roomId});
                    else
                        showMessageBox('解散房间不扣房卡，是否确定解散？', function () {
                            network.send(3003, {room_id: gameData.roomId});
                        }, null, false, false, true, true);
                    return;
                }

                showMessageBox('确定要申请解散房间吗？', function () {
                    network.send(3009, {room_id: gameData.roomId, is_accept: 1});
                }, null, true, false, true, true);
            });

            TouchUtil.setOnclickListener($('btn_jiesan'), function () {
                if (window.inReview)
                    network.send(3003, {room_id: gameData.roomId});
                else
                    var is_club = gameData['is_club'];
                showMessageBox('解散房间不扣房卡，是否确定解散？', function () {
                    if (is_club) {
                        network.send(3003, {daikai_room_id: gameData.roomId, force: true});
                    } else {
                        network.send(3003, {room_id: gameData.roomId});
                    }
                }, null, false, false, true, true);
            });

            TouchUtil.setOnclickListener($('info0'), function () {
                that.showPlayerInfoPanel(0);
            });
            TouchUtil.setOnclickListener($('info1'), function () {
                that.showPlayerInfoPanel(1);
            });
            TouchUtil.setOnclickListener($('info2'), function () {
                that.showPlayerInfoPanel(2);
            });
            TouchUtil.setOnclickListener($('info3'), function () {
                that.showPlayerInfoPanel(3);
            });

            TouchUtil.setOnclickListener($('info0.ti'), function () {
                that.tiAlert(position2uid[0]);
            });
            TouchUtil.setOnclickListener($('info1.ti'), function () {
                that.tiAlert(position2uid[1]);
            });
            TouchUtil.setOnclickListener($('info2.ti'), function () {
            });
            TouchUtil.setOnclickListener($('info3.ti'), function () {
                that.tiAlert(position2uid[3]);
            });


            //进入房间，包括自己和其他玩家进入房间
            this.addCustomListener(3002, function (data) {
                gameData.last3002 = data;
                gameData.playerNum = data['max_player_cnt'];
                if (isReplay) {
                    mapId = data['map_id'];
                    gameData.mapId = data['map_id'];
                    gameData.wanfaDesp = data['desp'];
                }
                if (that.getRoomState() == ROOM_STATE_CREATED) {
                    gameData.ownerUid = data['owner'];
                    gameData.players = data['players'];
                    that.onPlayerEnterExit();
                }
                gameData.daikaiPlayer = data['daikai_player'];
                gameData.roomClubId = data['options'] ? data['options']['club_id'] : null;
                eventManager.dispatchEvent(EventKey.ClubPlayerEnterExit, data["players"]);
                eventManager.dispatchEvent(EventKey.ClubRoomPlayerStateRefresh);
            });
            //房间解散，被踢出房间，有玩家主动退出房间
            this.addCustomListener(3003, function (data) {
                var uid = data['uid'];
                if (uid == gameData.uid) {
                    // cc.director.runScene(new MainScene());
                    showBoard('HallBoard');
                    return;
                }
                if (that.getRoomState() == ROOM_STATE_ONGOING)
                    return;
                if (data['del_room']) {
                    var owner = uid2playerInfo[gameData.ownerUid];
                    if (owner) {
                        showAlert('房主' + (owner ? owner.nickname : data['nickname'] || '') + '已解散房间', function () {
                            // cc.director.runScene(new MainScene());
                            showBoard('HallBoard');
                        });
                    } else {
                        showAlert('代开房主已解散房间', function () {
                            // cc.director.runScene(new MainScene());
                            showBoard('HallBoard');
                        })
                    }
                }
                else {
                    var uid = data['uid'];
                    _.remove(gameData.players, function (player) {
                        return player.uid == uid;
                    });
                    that.onPlayerEnterExit();
                }
            });
            //准备
            this.addCustomListener(3004, function (data) {
                // if (that.getRoomState() != ROOM_STATE_ENDED)
                //     return;
                if (!data) {
                    return;
                }
                var uid = data['uid'];
                that.setReady(uid);
            });
            //房卡数有变动
            this.addCustomListener(3013, function (data) {
                gameData.numOfCards = data['numof_cards'];
            });
            // this.addCustomListener(3005, function (data) {
            // });
            //请求房间解散的反馈信息
            this.addCustomListener(3009, function (data, errorCode) {
                if (errorCode == -1) {
                    showAlert("长时间未开始,房间自动解散");
                    return
                }
                if (data["arr"] == null || data["arr"] == undefined || data["arr"] == '' || (data["arr"] && data["arr"].length == 0)) {
                    return;
                }
                // var that = this;
                var arr = data['arr'];
                var leftSeconds = data['left_sec'];
                leftSeconds = (leftSeconds < 0 ? 0 : leftSeconds);
                var byUserId = data['arr'][0].uid;
                if (that.isJiesan)
                    return;
                that.isJiesan = data['is_jiesan'];

                if (!that.RoomQuitWindow) {
                    that.RoomQuitWindow = showWindow('RoomQuitWindow', leftSeconds, arr, byUserId, data);
                } else {
                    that.RoomQuitWindow.setData(leftSeconds, arr, byUserId, data);
                }
                that.RoomQuitWindow.setVisible(true);

            });

            //轮到谁出牌指示
            this.addCustomListener(4000, function (data) {
                var uid = data['uid'];
                if (uid2position[uid] == 2) {
                    that.refreshSelfPaiArr();
                }
                that.throwTurn(uid2position[uid]);
            });

            //摸牌
            this.addCustomListener(4001, function (data) {
                baijiaoStep = 0;
                baijiaoArr = undefined;

                var uid = data['uid'];
                var paiId = data['pai_id'];
                var paiArr = data['pai_arr'];
                gameData.left_pai_num = data['left'];
                that._refreshRoundAndPai();
                var baiPaiArr = (data['bai_pai_arr'] || []);
                that.mopai(uid2position[uid], paiId, paiArr, baiPaiArr);
                if(uid2position[uid]==2 && g_krt_isting[uid]){
                    disableChupai = true;
                }else{
                    disableChupai = false;
                }

                //听牌提示
                if (that.hupaiTipData &&gameData.mapId == app.map_id.GanSu_KaErTiao) {
                    if(uid != gameData.uid){
                        that._HuTipLayer.setVisible(true);
                        var hupaiCards = that.hupaiTipData['' + that.chuPaiId];
                        that._HuTipLayer.initHuPaiTishiLayer(hupaiCards);
                    }else {
                        that._HuTipLayer.setVisible(false);
                    }

                }

            });

            //出牌
            this.addCustomListener(4002, function (data) {
                var uid = data['uid'];
                var idx = data['idx'];
                var paiId = data['pai_id'];
                that.chuPaiId = paiId;
                var paiArr = (data['pai_arr'] || []);
                var paiCnt = (data['pai_cnt'] || 0);
                var left = (data['left'] || 0);
                var row = uid2position[uid];
                var baiPaiArr = (data['bai_pai_arr'] || []);
                for (var i = 0; i < paiCnt; i++)
                    paiArr.push(0);
                cc.log("出牌 ： ", row, idx, paiId, paiArr, baiPaiArr);
                if (!data['fake']) network.stop()
                //牌颜色 状态重置
                if (uid == gameData.uid) {
                    that.resetSelfPaisState();
                }
                that.chuPai(row, idx, paiId, paiArr, baiPaiArr, data['fake']);

            });
            // 其他玩家吃碰杠胡过
            this.addCustomListener(4003, function (data) {
                cc.log(that.getPai(2, 13).x)
                var uid = data['uid'];
                var fromUid = data['from_uid'];
                var paiId = data['pai_id'];
                var op = data['op'];
                var chi = op[0];
                var peng = op[1];
                var gang = op[2];
                var hu = op[3];
                var ting = op[4];
                if (chi) that.chiPengGangHu(OP_CHI, uid2position[uid], paiId, uid2position[fromUid], data);
                if (peng) that.chiPengGangHu(OP_PENG, uid2position[uid], paiId, uid2position[fromUid], data);
                if (gang) that.chiPengGangHu(OP_GANG, uid2position[uid], paiId, uid2position[fromUid], data);
                if (hu) {
                    g_ting_data[uid] = [];
                    that.chiPengGangHu(OP_HU, uid2position[uid], paiId, uid2position[fromUid], data);
                    that.hideChiPengGangHu();
                }
                if (!chi && !peng && !gang && !hu)
                    that.chiPengGangHu(OP_PASS, uid2position[uid], paiId, uid2position[fromUid], data);
                if (ting) {
                    g_krt_isting[uid] = true;
                    // that.tingOperatePais();
                    $('info' + uid2position[uid] + '.liang').setVisible(true);
                }
            });
            // 自己能吃碰杠胡
            this.addCustomListener(4004, function (data) {
                var uid = data['uid'];
                var paiId = data['pai_id'];
                var op = data['op'];
                var row = uid2position[uid];
                that.showChiPengGangHu(row, paiId, op[0], op[1], op[2], op[3], op[4], data);
            });

            this.addCustomListener(4005, this._onChiPengGangHuTing.bind(this));

            this.addCustomListener(40044, function (data) {
                var arr = data['arr'];
                for (var i = 0; i < arr.length; i++) {
                    var uid = arr[i]['data']['uid'];
                    var paiId = arr[i]['data']['pai_id'];
                    var op = arr[i]['data']['op'];
                    var row = uid2position[uid];
                    that.showChiPengGangHu(row, paiId, op[0], op[1], op[2], op[3], op[4], data);
                }
            });

            // 结算
            this.addCustomListener(4008, function (data) {
                that.hupaiTipData = null;
                if(that._HuTipLayer){
                    that._HuTipLayer.setVisible(false);
                }
                that._jiesuan_data = deepCopy(data);
                that._refreshRoomState(majiang.RoomState.ENDED);

                that.jiesuan(data);
                if (!isReplay) {
                    $('timer').setVisible(true);
                    $('timer2').setVisible(true);
                }
                that.setHuTipVisible(false);

                that._openJiesuanLayer();
            });

            // 总结算
            this.addCustomListener(4009, function (data) {
                that.zongJiesuan(data);

                if (that.RoomQuitWindow && cc.sys.isObjectValid(that.RoomQuitWindow)) {
                    that.RoomQuitWindow.setVisible(false);
                }
            });

            //祝贺语
            this.addCustomListener(4010, function (data) {
                var msg = data.msg;
                that.showToast(decodeURIComponent(msg));
            });
            this.addCustomListener(4011, function (data) {
            });
            this.addCustomListener(4012, function (data) {
            });

            //玩家在线状态改变
            this.addCustomListener(4020, function (data) {
                var uid = data['uid'];
                var isOffline = data['is_offline'];
                that.playerOnloneStatusChange(uid2position[uid], isOffline);
            });
            //继续玩，下一局开局
            this.addCustomListener(4200, function (data) {
                eventManager.dispatchEvent(EventKey.ClubRoomGameStart);
                g_ting_data = {};
                g_krt_isting = {};

                that._hideReady();
                var clubTablesLayer = that.getChildByName('clubTablesLayer');
                if (clubTablesLayer) {
                    clubTablesLayer.removeFromParent(true);
                }
                var paiArr = data['paiArr'];
                var zhuangUid = data['zhuang_uid'];
                gameData.zhuangUid = zhuangUid;
                gameData.totalRound = data['total_round'];
                gameData.curRound = data['cur_round'];
                gameData.leftRound = gameData.totalRound - gameData.curRound
                that._refreshRoundAndPai();
                that.initExtraMapData(data, false);

                that._refreshRoomState(majiang.RoomState.ONGOING);
                that.clearTable4StartGame(true);
                that.fapai(paiArr);
                that.setZhuang(uid2position[zhuangUid]);

                if (that.afterGameStart)
                    that.afterGameStart();
            });

            this.addCustomListener(4041, function (data, errCode) {
            });

            //听牌提示
            this.addCustomListener(4062, function (data) {
                data = data || g_last_net_data[4062];
                g_last_net_data[4062] = data;
                baijiaoStep = 0;
                that.showTishiTip(data);
                that.hupaiTipData = data.tishi;
                if (g_krt_isting[data.uid]) {
                    that.tingOperatePais();
                }
            });
            //4109 摆叫
            this.addCustomListener(4109, function (data) {
                //{'room_id':481375,'uid':308,
                // 'baijiao':[{'2':[12],'ting_pai_arr':[12]},{'5':[12],'ting_pai_arr':[12]},{'12':[2,2,2,3,3,3,4,4,4,5],'ting_pai_arr':[2,3,4,5,6]}]}

                if (data.uid == gameData.uid  &&  !isReplay) {
                    if (data.baijiao) {
                        baijiaoStep = 1;
                        that.showBaijiao(data);
                    } else if (data.baipai_arr) {
                        that.removeBaijiao();
                    }
                }
                // {"code":4109,"data":{"room_id":187985,"uid":253,"baipai_arr":[19],"ting_pai_arr":[19]},"errorCode":0}
                if (data.ting_pai_arr) {
                    g_ting_data[data.uid] = data.ting_pai_arr || data.tingpai_arr || []
                    //播放摆拍动画
                    playEffect('vbai', position2sex[data.uid]);
                    that.playChiPengGangHuAnim(uid2position[data.uid], 99, false)//摆拍动画
                    // network.stop();
                    // that.scheduleOnce(function () {
                    var row = uid2position[data.uid]
                    if ($('info' + row + '.bai')) {
                        $('info' + row + '.bai').setTexture(majiang_gs.res.bai_png);
                        $('info' + row + '.bai').setVisible(true);
                    }
                    //     network.start();
                    // }, 0.6)

                    if (isReplay) {
                        var node = $('cpghRep' + row + '.sp_6');

                        var touch_node = new cc.Node();
                        $('cpghRep' + row).addChild(touch_node);
                        touch_node.setPosition(node.getPositionX(), node.getPositionY() - 40);

                        var touch_sp0 = new cc.Sprite(res.touch0);
                        var touch_sp1 = new cc.Sprite(res.touch1);
                        touch_node.addChild(touch_sp0);
                        touch_node.addChild(touch_sp1);
                        touch_sp1.setVisible(false);

                        touch_node.runAction(cc.sequence(cc.delayTime(0.5), cc.callFunc(function () {
                            touch_sp0.setVisible(false);
                            touch_sp1.setVisible(true);
                        }), cc.delayTime(0.818), cc.callFunc(function () {
                            touch_node.removeFromParent();
                            $('cpghRep' + row).setVisible(false);
                        })));
                    }
                }
            });

            //及时算分
            this.addCustomListener(4066, function (data) {
                // todo data格式recv: {"code":4066,"data":{"scores":[{"uid":11, "score":-100, "total":900}, {"uid":1897, "score":-100, "total":900}, {"uid":5059, "score":100, "total":1100}, {"uid":5060, "score":100, "total":1100}]}}
                if (data && data['scores']) {
                    var scores = data['scores'];
                    for (var i = 0; i < scores.length; i++) {
                        var row = uid2position[scores[i]['uid']];
                        that.showChangeScore(row, scores[i]['score']);
                        $('info' + row + '.lb_score').setString(scores[i]['total']);
                    }
                }
            });


            network.start();

            if(gameData.mapId == app.map_id.GanSu_KaErTiao){
                this._HuTipLayer = new MaHuTipLayer();
                this._HuTipLayer.setPositionX(this._HuTipLayer.getPositionX() + cc.winSize.width / 2 - 1280 / 2);
                this.addChild(this._HuTipLayer);
                this._HuTipLayer.setVisible(false);
            }


            isCCSLoadFinished = true;

            // playMusic();

            var setting_bgm = settingData.local_bgMusic[gameData.mapId] || 1;
            playMusic("vbg_ma" + setting_bgm);
        },

        setupPlayers: function () {
            var that = this;
            if (mRoom.isReplay) {
                gameData.players = mRoom.replayData.users;
            }
            var data = gameData.players || [];
            var pos = 0;
            if (mRoom.isReplay == true) {
                pos = 0;
            } else {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].uid == gameData.uid) {
                        pos = i;
                    }
                }
            }
            this.pos0 = pos;
            this.pos1 = (pos + 1) % gameData.playerNum;
            this.pos2 = (pos + 2) % gameData.playerNum;
            this.pos3 = (pos + 3) % gameData.playerNum;

        },
        HuTypeAnimation: function (row, arr) {
            var that = this;
            if (arr.length > 0) {
                var huType = arr.shift();
                var typeSprite = new cc.Sprite('res/table/hu_type/' + huType + '.png');
                $('info_n' + row).addChild(typeSprite);
                typeSprite.runAction(
                    cc.sequence(
                        cc.moveBy(1.2, cc.p(0, 150)).easing(cc.easeOut(2.0)),
                        cc.callFunc(function () {
                            typeSprite.removeFromParent(true);
                            that.HuTypeAnimation(row, arr);
                        })
                    )
                );
                $('hu_type_layer').setVisible(true);
            } else {
                $('hu_type_layer').setVisible(false);
            }
        },
        baijiaoLastStep: function (data, baipaiArr) {
            baijiaoArr = baipaiArr;
            var i = 2;
            for (var j = 0; j <= 13; j++) {
                var pai = this.getPai(i, j);
                if (pai.isVisible()) {

                    var userData = pai.getUserData();
                    // cc.log(j, "set up ---- false", userData)
                    userData.isUp = false;
                    userData.isUpping = false;
                    userData.isDowning = false;
                    pai.stopAllActions();
                    pai.setOpacity(255);
                }
            }
            this.recalcPos(2)

            this.checkMyPaiColor4SC(data);
            baijiaoStep = 2;
        },
        getBaijiaoStep: function () {
            return baijiaoStep;
        },
        removeBaijiao: function () {
            if (this.baijiaoLayer) this.baijiaoLayer.removeFromParent()
            this.baijiaoLayer = undefined
        },
        showBaijiao: function (data) {
            // this.checkMyPaiColor4SC(data.baijiao);
            cc.log("showBaijiao");
            if (this.baijiaoLayer) {
                this.removeBaijiao();
            }
            this.baijiaoLayer = new BaijiaoLayer(data)
            this.addChild(this.baijiaoLayer, 100)
        },
        tingOperatePais: function () {
            if (!gameData.huTipData || mapId == app.map_id.GanSu_BaiJiao)return;
            var that = this;
            var data = gameData.huTipData;
            for (var i = 0; i < 14; i++) {
                (function (i) {
                    var cardSprite = that.getPai(2, i);
                    var userData = cardSprite.getUserData();
                    var paiId = userData.pai;
                    var hucards = null;
                    for (var cards in data.tishi) {
                        if (parseInt(cards) == parseInt(paiId)) {
                            hucards = data.tishi[cards];
                            break;
                        }
                    }
                    that.filterMyPai(2, i, !!hucards ? 1 : 0)
                })(i);
            }
        },
        hideTishiTip: function () {
            for (var i = 0; i < 14; i++) {
                var cardSprite = this.getPai(2, i);
                if (cardSprite.getChildByName('hucardSprite')) {
                    cardSprite.getChildByName('hucardSprite').setVisible(false);
                }
            }
        },
        showTishiTip: function (data) {
            var that = this;
            if (data == null || hasChupai || disableChupai) return;
            gameData.huTipData = data;
            //胡牌提示
            for (var i = 0; i < 14; i++) {
                (function (i) {
                    var cardSprite = that.getPai(2, i);
                    var userData = cardSprite.getUserData();
                    var paiId = userData.pai;
                    var hucards = null;
                    for (var cards in data.tishi) {
                        if (parseInt(cards) == parseInt(paiId)) {
                            hucards = data.tishi[cards];
                            break;
                        }
                    }
                    var hucardSprite;
                    if (cardSprite.getChildByName('hucardSprite')) {
                        hucardSprite = cardSprite.getChildByName('hucardSprite');
                        hucardSprite.setPosition(cardSprite.getContentSize().width / 2, cardSprite.getContentSize().height + 15);
                    } else {
                        hucardSprite = new cc.Sprite(majiang_gs.res.hupaitip_jiao1);
                        hucardSprite.setPosition(cardSprite.getContentSize().width / 2, cardSprite.getContentSize().height + 15);
                        hucardSprite.setName('hucardSprite');
                        cardSprite.addChild(hucardSprite);
                    }
                    var duration = 2;
                    hucardSprite.setVisible(!!hucards && mapId != app.map_id.GanSu_BaiJiao);

                    //TODO
                    //hucardSprite.setVisible(false);

                    // hucardSprite.runAction(new cc.RepeatForever(cc.sequence(
                    //     cc.spawn(cc.moveBy(duration, 0, 10), cc.fadeTo(duration, 188)),
                    //     cc.spawn(cc.moveBy(duration, 0, -10), cc.fadeTo(duration, 255))
                    // )));
                    var userData = cardSprite.getUserData();
                    userData.hucards = hucards;
                })(i);
            }
        },
        getVersion: function () {
            var versiontxt = window.curVersion;
            if (isReplay) {
                versiontxt = '';
            }
            var version = new ccui.Text();
            version.setFontSize(15);
            version.setTextColor(cc.color(255, 255, 255));
            version.setPosition(cc.p(cc.winSize.width - 80, 10));
            version.setAnchorPoint(cc.p(1, 0.5));
            version.setString(versiontxt);
            this.addChild(version, 2);
        },
        tiAlert: function (destUid) {
            showMessageBox('是否踢出【' + uid2playerInfo[destUid].nickname + '】该玩家？', function () {
                network.send(3010, {room_id: gameData.roomId, dest_uid: destUid});
            }, function () {
            });
        },
        onExit: function () {
            if (this.chiLayer)
                this.chiLayer.release();

            network.removeListeners([
                3002, 3003, 3004, 3008, 3200,
                4000, 4001, 4002, 4003, 4004, 4008, 4009, 4020, 4200
            ]);
            window.soundQueue = [];
            cc.Layer.prototype.onExit.call(this);

            network.removeListenersForTarget(this);
        },

        onPlayerEnterExit: function () {
            var that = this;
            var players = gameData.players;
            for (var i = 0; i < players.length; i++) {
                var player = players[0];
                if (player.uid != gameData.uid) {
                    players.splice(0, 1);
                    players.push(player);
                }
                else
                    break;
            }
            //开始位置加
            $('timer').setUserData({delta: i});
            uid2position = {};
            for (var i = 0, j = 2; i < players.length; i++, j++) {
                var player = players[i];
                var k = {
                    4: {'0': 0, '1': 3, '2': 2, '3': 1},
                    3: {'0': 1, '1': 3, '2': 2},
                    2: {'0': 2, '1': 0}
                }[playerNum][j % playerNum];

                $('info' + k).setVisible(true);
                // $('info' + k + '.lb_nickname').setString(ellipsisStr(player['nickname'], (k == 0 || k == 2
                //     ? 7
                //     : 5)));
                $('info' + k + '.lb_nickname').setVisible(false)
                if (this._room_state === majiang.RoomState.CREATED) {
                    var is_ready = player['ready'] === 1;
                    $('info' + k + '.ok').setVisible(is_ready);
                    if (gameData.uid === player.uid) {
                        cc.log("btn_zhunbei ->> ", gameData.uid, is_ready);
                        safeVisible($('btn_zhunbei'), !is_ready);
                    }
                }
                safeString($('info' + k + '.lb_score'), player['total_score']);

                if (k != 2 && gameData.uid == gameData.ownerUid && that.getRoomState() == ROOM_STATE_CREATED) {
                    $('info' + k + '.ti').setVisible(true);
                }
                // loadImage(player['headimgurl'], $('info' + k + '.head'));
                loadImageToSprite(player['headimgurl'], $('info' + k + '.head'));
                uid2position[player.uid] = k;
                uid2playerInfo[player.uid] = player;
                position2uid[k] = player.uid;
                position2sex[k] = player.sex;
                position2playerArrIdx[k] = i;
            }

            for (; i < playerNum; i++, j++) {
                var k = {
                    4: {'0': 0, '1': 3, '2': 2, '3': 1},
                    3: {'0': 1, '1': 3, '2': 2},
                    2: {'0': 2, '1': 0}
                }[playerNum][j % playerNum];
                $('info' + k).setVisible(false);
            }

            if (playerNum == 3) {
                $('info0').setVisible(false);
                $('row1').y = 232; // todo 这里暂时写死
                // $('row3').y = 135; // todo 这里暂时写死
            }

            if (playerNum == 2) {
                $('info1').setVisible(false);
                $('info3').setVisible(false);
            }

            if (gameData.uid == gameData.ownerUid) {
                if (players.length < playerNum) {
                    $('btn_invite').setVisible(gameData.loginType != 'yk');
                    $('btn_yxks').setVisible(false);
                } else if (that.getRoomState() == ROOM_STATE_CREATED) {
                    //$('btn_invite').setVisible(false);
                    // $('btn_yxks').setVisible(gameData.loginType != 'yk');
                    $('btn_yxks').setVisible(false);
                }
            }
            if (isReplay) {
                $('btn_invite').setVisible(false);
            }


            that.setupPlayers();
        },
        calcPosConf: function () {
            for (var row = 0; row < 4; row++) {
                var a0 = $('row' + row + '.a0');
                posConf.paiA0PosBak[row] = a0.getPosition();
                posConf.paiA0ScaleBak[row] = [a0.getScaleX(), a0.getScaleY()];
                posConf.headPosBak[row] = $('info' + row).getPosition();

                if (row == 0 || row == 2) {
                    var a0 = $('row' + row + '.a0');
                    var a1 = $('row' + row + '.a1');
                    posConf.paiADistance.push(a1.getPositionX() - a0.getPositionX());
                    var b0 = $('row' + row + '.c0.b0');
                    var b1 = $('row' + row + '.c0.b1');
                    posConf.paiUsedDistance.push(b1.getPositionX() - b0.getPositionX());

                    posConf.downPaiPositionY = a0.getPositionY();
                    posConf.upPaiPositionY = a0.getPositionY() + UPPAI_Y;
                }
                else {
                    var a0 = $('row' + row + '.a0');
                    var a1 = $('row' + row + '.a1');
                    posConf.paiADistance.push(a1.getPositionY() - a0.getPositionY());
                    var b0 = $('row' + row + '.c0.b0');
                    var b1 = $('row' + row + '.c0.b1');
                    posConf.paiUsedDistance.push(b1.getPositionY() - b0.getPositionY());
                }
                var b0 = $('row' + row + '.g0.b0');
                var b2 = $('row' + row + '.g0.b2');
                if (!cc.sys.isObjectValid(b0) || !cc.sys.isObjectValid(b2)) {
                    return;
                }

                if (row == 0) posConf.groupWidth[0] = b0.getPositionX() + b0.getContentSize().width / 2 - (b2.getPositionX() - b2.getContentSize().width / 2);
                if (row == 2) posConf.groupWidth[2] = b2.getPositionX() + b2.getContentSize().width / 2 - (b0.getPositionX() - b0.getContentSize().width / 2);
                if (row == 1) posConf.groupHeight[1] = b2.getPositionY() + b2.getContentSize().height / 2 - (b0.getPositionY() - b0.getContentSize().height / 2);
                if (row == 3) posConf.groupHeight[3] = b0.getPositionY() + b0.getContentSize().height / 2 - (b2.getPositionY() - b2.getContentSize().height / 2);
            }
        },

        /**
         * 小结算数据
         * @private
         * */
        _jiesuan_data: null,


        /**
         * 房间状态
         * @private
         * */
        _room_state: majiang.RoomState.NONE,

        /**
         * 胡牌类型(4005)
         * @private
         * */
        _huType: 0,
        setRoomData: function (_data, roomDataType) {
            isReplay = (roomDataType == ROOM_DATA_TYPE.REPLAY);
            isReconnect = (roomDataType == ROOM_DATA_TYPE.RECONNECT);
            data = (isReplay || isReconnect) ? _data : null;
        },
        ctor: function (_data, _isReplay) {
            this._super();
            this._jiesuan_data = null;
            this._room_state = majiang.RoomState.CREATED;

            cc.sys.localStorage.setItem(NOW_PAGE_STAGE.STAGE_CREATE_LAYER, 0);
            cc.sys.localStorage.setItem(NOW_PAGE_STAGE.STAGE_pokerCLUB_LAYER + '_btn_clubId', 0);
            cc.sys.localStorage.setItem(NOW_PAGE_STAGE.STAGE_CLUB_LAYER, 0);

            var paibeiid = cc.sys.localStorage.getItem('paibeiid') || 0;
            this.changePaibei(paibeiid);

            clearVars();

            var that = this;
            forRows = function (cb) {
                if (playerNum == 4 || playerNum == 2)
                    cb.call(that, 0);
                if (playerNum != 2)
                    cb.call(that, 1);
                cb.call(that, 2);
                if (playerNum != 2)
                    cb.call(that, 3);
            };


            this.setRoomData(_data, _isReplay)
            var node = loadCCSTo(majiang_gs.res.MaScene_json, this, 'Scene');
            node.setAnchorPoint(cc.p(0.5, 0.5));
            node.setPosition(cc.p(cc.winSize.width / 2, cc.winSize.height / 2));
            this.getVersion();
            return true;
        },

        changePaibei: function (paibeiid) {
            cc.spriteFrameCache.removeSpriteFramesFromFile('res/submodules/majiang_gs/pai.plist');
            cc.spriteFrameCache.removeSpriteFramesFromFile('res/submodules/majiang_gs/pai_p.plist');
            cc.spriteFrameCache.removeSpriteFramesFromFile('res/submodules/majiang_gs/pai_y.plist');
            cc.spriteFrameCache.addSpriteFrames('res/submodules/majiang_gs/pai.plist');
        },
        startSignal: function () {
            var that = this;
            var interval = null;
            var lastDealy = -1;
            var func = function () {
                if (!that || !cc.sys.isObjectValid(that))
                    return clearInterval(interval);
                var delay = network.getLastPingInterval();
                if (delay == lastDealy)
                    return;
                //console.log('delay ' + delay);
                lastDealy = delay;
                if (delay < 100) $('signal').setTexture(signal3);
                else if (delay < 200) $('signal').setTexture(signal3);
                else if (delay < 300) $('signal').setTexture(signal2);
                else if (delay < 600) $('signal').setTexture(signal2);
                else $('signal').setTexture(signal1);
            };
            func();
            interval = setInterval(func, 200);
        },
        startTime: function () {
            var interval = null;
            var flag = true;
            var lbTime = $('lb_time');
            if (isReplay) {
                lbTime.setVisible(false);
                return;
            }
            var updTime = function () {
                //显示电池电量
                var battery = $('battery');
                var level = DeviceUtil.getBatteryLevel();
                if (cc.sys.isObjectValid(battery)) {
                    if (level == 100) {
                        battery.setTexture(res.battery5);
                    } else if (level > 75) {
                        battery.setTexture(res.battery4);
                    } else if (level > 50) {
                        battery.setTexture(res.battery3);
                    } else if (level > 25) {
                        battery.setTexture(res.battery2);
                    } else if (level > 0) {
                        battery.setTexture(res.battery1);
                    }
                }
                var date = new Date();
                var minutes = (date.getMinutes() < 10
                        ? '0'
                        : '') + date.getMinutes();
                var hours = (date.getHours() < 10
                        ? '0'
                        : '') + date.getHours();
                if (cc.sys.isObjectValid(lbTime))
                    lbTime.setString(hours + (flag
                            ? ':'
                            : ' ') + minutes);
                else if (interval)
                    clearInterval(interval);
                flag = !flag;
            };
            updTime();
            interval = setInterval(updTime, 1000);
        },
        isMyTurn: function () {
            return turnRow == 2;
        },
        getTurn: function () {
            for (var i = 0; i < 4; i++) {
                var node = $('timer.' + i);
                if (node.isVisible())
                    return (i + $('timer').getUserData().delta) % 4;
            }
            return -1;
        },
        throwTurnByUid: function (uid) {
            this.throwTurn(uid2position[uid]);
        },
        throwTurn: function (row) {
            turnRow = row;
            $('timer').setVisible(true);
            $('timer2').setVisible(true);
            for (var _j = 0; _j < 4; _j++) {
                var _arrow = $('timer.arrow' + _j);
                if (_arrow)
                    _arrow.setVisible(false);
                $('timer.dir_' + _j).setTextColor(_j == row ? cc.color(0, 0, 0) : cc.color(202, 202, 202));
            }
            var arrow = $('timer.arrow' + row);
            arrow.setTexture(res['t' + row]);
            arrow.setVisible(true);
            if (arrow.getNumberOfRunningActions() == 0)
                arrow.runAction(new cc.RepeatForever(cc.sequence(cc.fadeTo(0.5, 168), cc.fadeTo(0.5, 255))));

            if (row == 2)
                this.upPai(2, -1);
            this.hideTip();
            gameData.huTipData = null;

        },
        setPai: function (row, idx, val, isLittle, isStand, isVisible) {
            var pai = this.getPai(row, idx);

            var userData = pai.getUserData();
            var paiName = getPaiNameByRowAndId(row, val, isLittle, val > 0
                ? false
                : (isReplay || roomState == ROOM_STATE_ENDED
                    ? false
                    : isStand));
            userData.pai = val;
            // cc.log(row, "set pai id =", val, isVisible)
            setSpriteFrameByName(pai, paiName, majiang_gs.res.pai0plist);
            if (!_.isUndefined(isVisible)) {
                if (isVisible) {
                    pai.setVisible(true);
                } else {
                    pai.setVisible(false);
                }
            }
            return pai;
        },
        getPai: function () {
            var cache = {};
            return function (row, id) {
                cache[row] = cache[row] || {};
                if (cache[row][id])
                    return cache[row][id];
                var node = $('row' + row + '.a' + id);
                if (!node) {
                    var a0 = $('row' + row + '.a0');
                    node = duplicateNode(a0, true);
                    if (row == 0 || row == 2) node.setPositionX(posConf.paiADistance[row] * id + a0.getPositionX());
                    if (row == 1 || row == 3) node.setPositionY(posConf.paiADistance[row] * id + a0.getPositionY());
                    node.setName('a' + id);
                    a0.getParent().addChild(node, (row == 1
                        ? -id
                        : 0));
                }
                var userData = node.getUserData();
                if (!userData)
                    userData = {};
                userData.idx = id;
                node.setUserData(userData);
                cache[row][id] = node;
                return node;
            };
        },
        getPaiId: function (row, id) {
            var userData = this.getPai(row, id).getUserData();
            return userData.pai;
        },
        setGChi: function (row, j, paiId, oriPaiId) {
            var a = 0, b = 0, c = 0;
            if (_.isArray(paiId)) {
                a = paiId[0];
                b = paiId[1];
                c = paiId[2];
            }
            else {
                if (paiId - 1 == oriPaiId) {
                    a = paiId;
                    b = paiId - 1;
                    c = paiId + 1;
                }
                if (paiId == oriPaiId) {
                    a = paiId - 1;
                    b = paiId;
                    c = paiId + 1;
                }
                if (paiId + 1 == oriPaiId) {
                    a = paiId - 1;
                    b = paiId + 1;
                    c = paiId;
                }
            }
            this.setGPai(row, j, 0, a);
            this.setGPai(row, j, 1, b);
            this.setGPai(row, j, 2, c);
            $('row' + row + '.g' + j + '.b' + 3).setVisible(false);
            $('row' + row + '.g' + j).setVisible(true);
        },
        addNarrow: function (pai, row, fromrow) {
            if (fromrow == undefined)return;
            if (pai && cc.sys.isObjectValid(pai) && pai.isVisible()) {
                var from = posConf.gPaiPos[row][fromrow];
                if (from == undefined) {
                    from = 3;
                }
                var texture = res['narrow_' + from];
                if (texture) {
                    var narrow = pai.getChildByName('narrow');
                    if (narrow) {
                        narrow.setTexture(texture);
                    } else {
                        narrow = new cc.Sprite(texture);
                        pai.addChild(narrow);
                        narrow.setName('narrow');
                    }

                    // narrow.runAction(cc.rotateTo(0, posConf.huFromAngle[row]));
                    narrow.setRotation(posConf.huFromAngle[row]);
                    narrow.setPosition(posConf.fromPos[row]);
                }
            }
        },

        setGPai: function (row, g, idx, val) {
            var pai = this.getGPai(row, g, idx);
            var userData = pai.getUserData();
            var paiName = getPaiNameByRowAndId(row, val, true);
            userData.pai = val;
            setSpriteFrameByName(pai, paiName, majiang_gs.res.pai0plist, 'pai');
        },
        setGPeng: function (row, j, paiId, fromRow) {
            for (var k = 0; k < 3; k++)
                this.setGPai(row, j, k, paiId);
            $('row' + row + '.g' + j + '.b' + 3).setVisible(false);
            $('row' + row + '.g' + j).setVisible(true);
            this.addNarrow($('row' + row + '.g' + j + '.b' + 0), row, fromRow);
        },
        setGHide: function (row, j) {
            for (var k = 0; k < 3; k++)
                this.setGPai(row, j, k, 0);
            $('row' + row + '.g' + j + '.b' + 3).setVisible(false);
            $('row' + row + '.g' + j).setVisible(true);
        },
        setGGang: function (row, j, upPaiId, downPaiId, fromRow) {
            if (downPaiId == 0) {
                upPaiId = upPaiId;//row == 2?upPaiId:0;
            }
            this.setGPai(row, j, 3, upPaiId);
            $('row' + row + '.g' + j + '.b' + 3).setVisible(true);
            for (var k = 0; k < 3; k++)
                this.setGPai(row, j, k, downPaiId);
            $('row' + row + '.g' + j).setVisible(true);
            this.addNarrow($('row' + row + '.g' + j + '.b' + 0), row, fromRow);
        },
        setGJiaGang: function (row, paiId, fromRow) {
            for (var j = 0; j < 4; j++)
                if ($('row' + row + '.g' + j).isVisible() &&
                    this.getGPaiId(row, j, 0) == paiId &&
                    this.getGPaiId(row, j, 0) == this.getGPaiId(row, j, 1) &&
                    this.getGPaiId(row, j, 1) == this.getGPaiId(row, j, 2)) {
                    this.setGPai(row, j, 3, paiId);
                    this.getGPai(row, j, 3).setVisible(true);
                    break;
                }
            this.addNarrow($('row' + row + '.g' + j + '.b' + 0), row, fromRow);
        },
        getGPai: function () {
            var cache = {};
            return function (row, g, id) {
                cache[row] = cache[row] || {};
                cache[row][g] = cache[row][g] || {};
                if (cache[row][g][id])
                    return cache[row][g][id];
                var group0 = $('row' + row + '.g' + 0);
                var groupNode = $('row' + row + '.g' + g);
                if (!groupNode) {
                    groupNode = duplicateNode(group0, true);
                    if (row == 0 || row == 2) groupNode.setPositionX(group0.getPositionX() + posConf.groupWidth[row] * g + posConf.paiADistance[row] * g);
                    if (row == 1 || row == 3) groupNode.setPositionY(group0.getPositionY() + posConf.groupHeight[row] * g + posConf.paiADistance[row] * g);
                    groupNode.setName('g' + g);
                    groupNode.setVisible(false);
                    group0.getParent().addChild(groupNode);
                }
                var node = $('row' + row + '.g' + g + '.b' + id);
                cache[row][g][id] = node;
                return node;
            };
        },
        getGPaiId: function (row, g, id) {
            var userData = $('row' + row + '.g' + g + '.b' + id).getUserData();
            return userData.pai;
        },
        checkPaiAmount: function () {
            if (cc.sys.isNative)
                return;
            var amount = 0;
            var row = 2;
            for (var j = 0; j < 4; j++) {
                var g = $('row' + row + '.g' + j);
                if (!g || !$('row' + row + '.g' + j).isVisible())
                    break;
                else {
                    amount += 3;
                    cc.log("+=3");
                }
            }
            for (var j = 0; j < 14; j++)
                if (this.getPai(row, j).isVisible()) {
                    amount += 1;
                    cc.log("+=1");
                }

            if (amount < 13 || amount > 14) {
                cc.error('你的牌数量可能不对: ' + amount + ', 数一下');
                showMessageBox("错误==牌对不上")
            }
        },
        recalcPos: function (row) {
            var g0 = $('row' + row + '.g' + 0);
            var g0b0pos = getPositionRelativeToParent(this.getGPai(row, 0, 0), 2);
            for (var i = 1; i < 4; i++) {
                var g = $('row' + row + '.g' + i);
                if (g && g.isVisible()) {
                    if (row == 0 || row == 2)
                        g.setPositionX(g0.getPositionX() + (posConf.groupWidth[row] * i + posConf.groupDistance[row] * i) * (row == 2
                                ? 1
                                : -1));
                    if (row == 1 || row == 3)
                        g.setPositionY(g0.getPositionY() + (posConf.groupHeight[row] * i + posConf.groupDistance[row] * i) * (row == 1
                                ? 1
                                : -1));
                }
                else
                    break;
            }
            var k = i;
            var m = (k > 1 || g0.isVisible()
                ? 1
                : 0);

            var a0 = this.getPai(row, 0);
            var to = 0;
            var p = (row == 1 || row == 2
                ? 1
                : -1);
            if (row == 0 || row == 2) to = !m
                ? posConf.paiA0PosBak[row].x
                : g0b0pos.x + (posConf.groupWidth[row] * k + posConf.groupDistance[row] * k + posConf.groupToFirstPaiDistance[row]) * p;
            if (row == 1 || row == 3) to = !m
                ? posConf.paiA0PosBak[row].y
                : g0b0pos.y + (posConf.groupHeight[row] * k + posConf.groupDistance[row] * k + posConf.groupToFirstPaiDistance[row]) * p;
            if (row == 0 || row == 2) a0.setPositionX(to);
            if (row == 1 || row == 3) a0.setPositionY(to);


            for (var i = 0; i <= 13; i++) {
                var a = this.getPai(row, i);
                var isBai = false;//a.getChildByName('bai');
                var bai = a.getChildByName('bai');
                if (bai && i != 13) {
                    isBai = bai.isVisible();
                }
                var userData = a.getUserData();
                if (row == 0) {
                    a.setPosition((isBai ? -20 : 0) + a0.getPositionX() + i * posConf.paiADistance[row] + (a.getUserData().pai > 0) * i * posConf.paiALiangDistance[row], a0.getPositionY());
                }
                if (row == 2) {
                    a.setPositionX((isBai ? 20 : 0) + a0.getPositionX() + i * posConf.paiADistance[row] + (a.getUserData().pai > 0) * i * posConf.paiALiangDistance[row]);
                    if (!userData.isUpping && !userData.isDowning) {
                        a.setPositionY(userData.isUp
                            ? posConf.upPaiPositionY
                            : posConf.downPaiPositionY);
                        // cc.log(a.y);
                    }
                }
                if (row == 1 || row == 3) {
                    a.setPosition(a0.getPositionX(), a0.getPositionY() + i * posConf.paiADistance[row] + (a.getUserData().pai > 0) * i * posConf.paiALiangDistance[row]);
                }
            }

            // recalc pai 13 position
            for (var i = 12; i >= 0; i--) {
                var pai = this.getPai(row, i);
                if (pai && pai.isVisible()) {
                    var userData = pai.getUserData();
                    var p = (row == 1 || row == 2
                        ? 1
                        : -1);

                    if (row == 0) this.getPai(row, 13).setPosition(pai.getPositionX() + posConf.paiADistance[row] + posConf.paiMopaiDistance[row] * p, a0.getPositionY());
                    // cc.log("for ->  ", pai.getPositionX() + posConf.paiADistance[row] + posConf.paiMopaiDistance[row] * p);
                    if (row == 2) {
                        this.getPai(row, 13).setPositionX(pai.getPositionX() + posConf.paiADistance[row] + posConf.paiMopaiDistance[row] * p);
                        if (!userData.isUpping && !userData.isDowning) {
                            a.setPositionY(userData.isUp
                                ? posConf.upPaiPositionY
                                : posConf.downPaiPositionY);

                            // cc.log(i, userData.isUp, userData.isUp? posConf.upPaiPositionY: posConf.downPaiPositionY);
                        }
                        //cc.log(this.getPai(row, 13).x);
                    }
                    if (row == 1 || row == 3) this.getPai(row, 13).setPosition(a0.getPositionX(), pai.getPositionY() + posConf.paiADistance[row] + posConf.paiMopaiDistance[row] * p);
                    break;
                }
            }
            //cc.log(this.getPai(row, 13).x, "row--", row)

            posConf.paiPos[row] = [];
            for (var i = 0; i < 14; i++) {
                posConf.paiPos[row].push(this.getPai(row, i).getPosition());
            }
            for (var i = 14; i < 18; i++) {
                var pai = $('row' + row + '.a' + i);
                if (pai)
                    pai.setVisible(false);
            }
        },
        hidePai: function (row, id) {
            this.getPai(row, id).setVisible(false);
        },
        getPaiArr: function () {
            return this.getPaiArrOfRow(2);
        },
        getUpPaiArr: function () {
            var arr = [];
            for (var j = 0; j < 14; j++) {
                var pai = this.getPai(2, j);
                var userData = pai.getUserData();
                if (userData.pai > 0) {
                    if (userData.isUp && !userData.isDowning) {
                        arr.push(userData.pai);
                    } else if (userData.isUpping) {
                        arr.push(userData.pai);
                    }
                }

            }
            return arr;
        },
        getPaiArrOfRow: function (row) {
            var arr = [];
            for (var j = 0; j < 14; j++) {
                var pai = this.getPai(row, j);
                var userData = pai.getUserData();
                if (userData.pai > 0)
                    arr.push(userData.pai);
            }
            return arr;
        },
        getPaiCoutOfRow: function (row) {
            var count = 0;
            for (var i = 0; i < 14; i++) {
                var pai = this.getPai(row, i);
                if (pai.isVisible()) {
                    count += 1;
                }
            }
            return count;
        },
        addUsedPai: function () {
            var cache = {};
            var that = this;
            return function (row, val, fake) {
                cache[row] = cache[row] || {};
                for (var idx = 0; idx < 60; idx++) {
                    // var j = idx + parseInt(idx / 8) * 2;
                    var j = idx;
                    var pai = cache[row][j] || $('row' + row + '.c0.b' + j);
                    if (!pai) {
                        var k = parseInt(j / 10) * 10;
                        var b = $('row' + row + '.c0.b' + k);
                        if (!b) {
                            var b0 = $('row' + row + '.c0.b0');
                            var b10 = $('row' + row + '.c0.b10');
                            b = duplicateNode(b0);
                            b.setName('b' + k);
                            if (row == 0) b.setPositionY(parseInt(j / 10) * (b10.getPositionY() - b0.getPositionY()) + b0.getPositionY());
                            if (row == 1) b.setPositionX(parseInt(j / 10) * (b10.getPositionX() - b0.getPositionX()) + b0.getPositionX());
                            if (row == 2) b.setPositionY(parseInt(j / 10) * (b10.getPositionY() - b0.getPositionY()) + b0.getPositionY());
                            if (row == 3) b.setPositionX(parseInt(j / 10) * (b10.getPositionX() - b0.getPositionX()) + b0.getPositionX());
                            b0.getParent().addChild(b);
                            if (row == 2)
                                b.setLocalZOrder(k * -1);
                            pai = b;
                            pai.setVisible(false);
                        }
                        if (!pai) {
                            pai = duplicateNode(b);
                            if (row == 0 || row == 2) pai.setPositionX(posConf.paiUsedDistance[row] * (j - k) + b.getPositionX());
                            if (row == 1 || row == 3) pai.setPositionY(posConf.paiUsedDistance[row] * (j - k) + b.getPositionY());
                            pai.setName('b' + j);
                            pai.setVisible(false);
                            b.getParent().addChild(pai, j * posConf.paiUsedZOrder[row][k]);
                            cache[row][j] = pai;
                        }

                    }



                    if (!pai.isVisible()) {
                        //var userData = pai.getUserData();
                        var paiName = getPaiNameByRowAndId(row, val, true);
                        //userData.pai = val;
                        setSpriteFrameByName(pai, paiName, majiang_gs.res.pai0plist);
                        pai.setVisible(true);

                        Filter.remove(pai);
                        recoverColor(pai);//恢复颜色
                        pai.isFake = fake;
                        pai.setUserData({idx: j, pai: val});
                        return pai;
                    } else if ((pai.isVisible() && pai.isFake)) {
                        var paiName = getPaiNameByRowAndId(row, val, true);
                        //userData.pai = val;
                        setSpriteFrameByName(pai, paiName, majiang_gs.res.pai0plist);
                        pai.setVisible(true);

                        Filter.remove(pai);
                        recoverColor(pai);//恢复颜色
                        pai.isFake = fake;
                        pai.setUserData({idx: j, pai: val});
                        return pai;
                    }
                }
            };
        },
        removeOneTopUsedPai: function (row, paiId) {
            for (var j = 47; j >= 0; j--) {
                var pai = $('row' + row + '.c0.b' + j);
                if (pai && pai.isVisible()) {
                    var userData = pai.getUserData();
                    if (!_.isUndefined(paiId) && userData.pai != paiId)
                        return;
                    userData.pai = 0;
                    userData.fake = undefined;
                    pai.setVisible(false);
                    break;
                }
            }
            this.hideArrow();
        },

        /**
         * 游戏中隐藏所有的准备
         * @private
         * */
        _hideReady: function () {
            for (var i = 0; i < 4; i++) {
                safeHide($('info' + i + '.ok'));
                safeHide($('info' + i + '.ti'));
                safeHide($('info' + i + '.btn_invite'));
            }
            safeHide($('btn_zhunbei'));
        },

        getRoomState: function () {
            return roomState;
        },

        /**
         * 刷新局数和剩余牌数
         * @param {Boolean} [is_show=true]
         * @private
         * */
        _refreshRoundAndPai: function (is_show) {
            if (cc.isUndefined(is_show)) {
                is_show = true;
            }
            //$('timer2.left_pai').setString('剩余\n' + gameData.left_pai_num);
            //$('timer2.Text_5').setString(gameData.leftRound || 0);
            //safeString($('timer2.left_round'), '局数\n' + gameData.cur_round + '/' + gameData.totalRound);

            safeString($('timer2.Text_2'), gameData.left_pai_num || 0);
            safeString($('timer2.Text_5'), gameData.leftRound);
            safeVisible($('timer'), is_show);
            safeVisible($('timer2'), is_show);
        },

        /**
         * 刷新房间状态
         * @param {Number} state
         * @private
         * */
        _refreshRoomState: function (state) {
            this._room_state = state;
            var arr = decodeURIComponent(gameData.wanfaDesp != 'null'
                ? gameData.wanfaDesp
                : '').split(',');
            if (arr.length >= 1)
                arr = arr.slice(0);
            var wanfaStr = arr.join(' ');
            if (isReplay) {
                $('btn_control_btns').setVisible(false);
            }
            if (this._room_state === majiang.RoomState.CREATED) {
                this.hideControlBtns(false);
                $('signal').setVisible(false);
                // $('setting').setVisible(false);
                // $('chat').setVisible(false);
                $('timer').setVisible(false);
                $('timer2').setVisible(false);
                // tn_c$('btn_invite').setVisible(gameData.loginType != 'yk' && gameData.uid == gameData.ownerUid);
                // $('bopyinfo').setVisible(gameData.loginType&&gameData.loginType != 'yk' && gameData.uid == gameData.ownerUid);

                $('btn_invite').setVisible(!window.inReview);
                if (isReplay) {
                    $('btn_invite').setVisible(false);
                }
                if (gameData.club_id && gameData.ownerUid == gameData.uid) {
                    $('btn_fanhui').setVisible(true);
                    $('btn_fanhui').setPositionY($('btn_fanhui').getPositionY() + 80);
                } else {
                    $('btn_fanhui').setVisible(gameData.uid != gameData.ownerUid);
                }
                $('btn_jiesan').setVisible(gameData.uid == gameData.ownerUid);
                $('btn_control_btns').setVisible(true);
                this.hideControlBtns();

                $('btn_mic').setVisible(!isReplay);
                $('lb_roomid').setString(gameData.roomId);
                $('lb_wanfa').setString(wanfaStr);
                $('lb_roomid').setVisible(true);

                $('timer2.Text_9').setString(gameData.roomId);
                $('timer2.Text_7').setString(mapId2Name(mapId));


                $('row0').setVisible(false);
                $('row1').setVisible(false);
                $('row2').setVisible(false);
                $('row3').setVisible(false);
                //$('btn_info').setVisible(false);
                //this.showLogo();
                if ($('btn_queding')) $('btn_queding').setVisible(false);
                if ($('btn_quxiao')) $('btn_quxiao').setVisible(false);
                if ($('btn_xuanzewancheng')) $('btn_xuanzewancheng').setVisible(false);
                for (var i = 0; i < 4; i++) {
                    $('info' + i).setPosition($('info_n' + i).getPosition());
                    $('info' + i + '.lb_nickname').setVisible(false);
                    $('info' + i + '.lb_score').setVisible(false);
                }
                this.hideArrow();
                disabledChuPaiIdMap = {};
            }
            if (this._room_state === majiang.RoomState.ONGOING) {
                var setting = $('setting');
                if (!setting || !cc.sys.isObjectValid(setting))
                    return network.disconnect();
                $('signal').setVisible(!isReplay);
                $('btn_invite').setVisible(false);
                $('btn_fanhui').setVisible(false);
                $('btn_jiesan').setVisible(false);
                $('lb_roomid').setVisible(false);
                $('lb_roomid_').setVisible(false);

                $('btn_control_btns').setVisible(true);
                this.hideControlBtns();

                // $('btn_control_btns').setVisible(false);
                // this.showControlBtns();
                $('btn_yxks').setVisible(false);
                $('btn_mic').setVisible(!isReplay);
                $('lb_roomid').setString(gameData.roomId);
                $('timer2.Text_9').setString(gameData.roomId);
                $('timer2.Text_7').setString(mapId2Name(mapId));
                $('lb_wanfa').setString(wanfaStr);
                $('row0.c0').setVisible(true);
                if ($('btn_queding')) $('btn_queding').setVisible(false);
                if ($('btn_quxiao')) $('btn_quxiao').setVisible(false);
                if ($('btn_xuanzewancheng')) $('btn_xuanzewancheng').setVisible(false);
                //$('lb_roomid').setVisible(false);
                $('row0').setVisible(true);
                $('row1').setVisible(true);
                $('row2').setVisible(true);
                $('row3').setVisible(true);
                safeHide($('btn_zhunbei'));

                $('row0.mid').removeAllChildren();
                $('row1.mid').removeAllChildren();
                $('row2.mid').removeAllChildren();
                $('row3.mid').removeAllChildren();

                for (var i = 0; i < 4; i++) {
                    if (roomState == ROOM_STATE_CREATED)
                        $('info' + i).runAction(cc.moveTo(0.5, posConf.headPosBak[i]));
                    else
                        $('info' + i).setPosition(posConf.headPosBak[i]);

                    $('info' + i + '.ok').setVisible(false);
                    $('info' + i + '.ti').setVisible(false);
                    $('info' + i + '.lb_nickname').setVisible(false);
                    $('info' + i + '.lb_score').setVisible(true);
                }

                if (isReplay) {
                    $('setting').setVisible(false);
                    $('chat').setVisible(false);
                }
            }
            if (this._room_state === majiang.RoomState.ENDED) {
                this.hideControlBtns();
                $('lb_wanfa').setString(wanfaStr);
                $('lb_roomid').setVisible(false);
                $('lb_roomid_').setVisible(false);
                if ($('btn_queding')) $('btn_queding').setVisible(false);
                if ($('btn_quxiao')) $('btn_xuanzewancheng').setVisible(false);
                if ($('btn_xuanzewancheng')) $('btn_xuanzewancheng').setVisible(false);
                $('timer2.Text_9').setString(gameData.roomId);
                $('timer2.Text_7').setString(mapId2Name(mapId));
                this.hideChiPengGangHu();
                this.hideArrow();
                disabledChuPaiIdMap = {};
            }
            roomState = this._room_state;
            eventManager.dispatchEvent(EventKey.ClubRoomStateChange, roomState);
        },
        setDuiArr: function (row, duiArr) {
            for (var j = 0; j < 4; j++) {
                var g = $('row' + row + '.g' + j);
                if (g && g.isVisible())
                    g.setVisible(false);
            }
            for (var j = 0; j < duiArr.length; j++) {
                var dui = duiArr[j];
                var fromRow = uid2position[dui['from_uid']];
                if (dui.type == 1) this.setGChi(row, j, dui['pai_arr']);
                if (dui.type == 2) this.setGPeng(row, j, dui['pai_arr'][0], fromRow);
                if (dui.type == 3) this.setGGang(row, j, dui['pai_arr'][0], dui['pai_arr'][0], fromRow);
                if (dui.type == 4) this.setGGang(row, j, dui['pai_arr'][0], 0, fromRow);
                if (dui.type == 5) this.setGHide(row, j);
            }
        },
        clearTable4StartGame: function (isInitPai, isReconnect, reconnectData) {
            var that = this;
            this.onPlayerEnterExit();
            if (isInitPai) {
                forRows(function (i) {
                    var a0 = $('row' + i + '.a0');
                    if (a0.getPosition().x != posConf.paiA0PosBak[i].x || a0.getPosition().y != posConf.paiA0PosBak[i].y) {
                        a0.setPosition(posConf.paiA0PosBak[i]);
                        for (var j = 1; j < 13; j++) {
                            var node = $('row' + i + '.a' + j);
                            if (i == 0 || i == 2) node.setPositionX(posConf.paiADistance[i] * j + a0.getPositionX());
                            if (i == 1 || i == 3) node.setPositionY(posConf.paiADistance[i] * j + a0.getPositionY());
                        }
                    }
                });
                for (var i = 0; i < 4; i++) {
                    for (var j = 0; j < 4; j++) {
                        this.getPai(i, j).setVisible(false);
                    }
                    for (var k = 0; k < 4; k++) {
                        var g = $('row' + i + '.g' + k);
                        if (g)
                            g.setVisible(false);
                    }
                    for (var k = 0; k < 4; k++) {
                        this.getGPai(i, 0, k).setUserData({idx: k});
                    }
                    $('row' + i + '.c0.b0').setVisible(false);
                    $('row' + i + '.c0.b1').setVisible(false);
                    $('row' + i + '.c0.b10').setVisible(false);
                }
                forRows(function (i) {
                    $('info' + i + '.liang').setVisible(false);
                    for (var j = 0; j < 14; j++) {
                        this.getPai(i, j).setOpacity(0);
                    }
                    var c0 = $('row' + i + '.c0');
                    if (i == 0)
                        c0.setLocalZOrder(50);
                    for (var j = 0; j < 100; j++) {
                        var t = $('b' + j, c0);
                        if (t) {
                            t.setUserData({idx: j});
                            t.setVisible(false);
                        }
                    }
                    for (var j = 0; j < 14; j++) {
                        var pai = this.getPai(i, j);
                        if (pai) {
                            var userData = pai.getUserData()
                            pai.getUserData().isLiang = true;
                            Filter.remove(pai);
                            var jin = pai.getChildByName('jin')
                            if (jin) {
                                jin.setVisible(false)
                            }
                            var bai = pai.getChildByName('bai')
                            if (bai) {
                                bai.setVisible(false)
                            }
                        }
                    }
                });
                that.setHuTipVisible(false);
            }

            $('cpghg').setVisible(false);
            $('timer').setVisible(false);

            //this.recalcPos(2);

            if (isReconnect) {
                hasChupai = reconnectData['has_chu'];
                that.setZhuang(uid2position[gameData.zhuangUid]);
                gameData.left_pai_num = reconnectData['left_pai_num'];
                this._refreshRoundAndPai();
                var playerPaiArr = reconnectData['player_pai'] || [];
                //提前初始化听牌列表
                for (var i = 0; i < playerPaiArr.length; i++) {
                    //ting_pai_arr
                    var playerPai = playerPaiArr[i];
                    if (playerPai['ting_pai_arr']) {
                        g_ting_data[playerPai.uid] = playerPai['ting_pai_arr']
                    }
                }
                for (var i = 0; i < playerPaiArr.length; i++) {
                    var playerPai = playerPaiArr[i];
                    var isOffline = !!playerPai['is_offline'];
                    if (isOffline) {
                        this.playerOnloneStatusChange(uid2position[playerPai.uid], isOffline);
                    }

                    var row = uid2position[playerPai.uid];
                    if (row != 2
                        && roomState == ROOM_STATE_ONGOING
                        && playerPai['pai_arr'].length == 0) {
                        for (var j = 0; j < playerPai['cur_pai_num']; j++)
                            playerPai['pai_arr'].push(0);
                    }
                    // if (row == 2 && playerPaiArr[i]['is_ting']) {
                    //     //afterLianging = true;
                    // }
                    if ($('info' + row + '.bai') && gameData.mapId == app.map_id.GanSu_BaiJiao) {
                        $('info' + row + '.bai').setTexture(majiang_gs.res.bai_png);
                        $('info' + row + '.bai').setVisible(playerPaiArr[i]['is_ting']);
                    }
                    if ($('info' + row + '.liang') && gameData.mapId == app.map_id.GanSu_KaErTiao) {
                        // $('info' + row + '.liang').setTexture(majiang_gs.res.bai_png);
                        $('info' + row + '.liang').setVisible(playerPaiArr[i]['is_ting']);
                        g_krt_isting[playerPai.uid] = playerPaiArr[i]['is_ting'];//听牌
                    }

                    that.setPaiArrOfRow(row, playerPai['pai_arr'], (row != 2), (row != 2), undefined, playerPai['bai_pai_arr']);

                    var usedPaiArr = playerPaiArr[i]['used_pai_arr'];
                    for (var j = 0; j < usedPaiArr.length; j++)
                        this.addUsedPai(row, usedPaiArr[j]);
                    var duiArr = playerPaiArr[i]['dui_arr'];
                    this.setDuiArr(row, duiArr);

                }

                forRows(function (i) {
                    this.recalcPos(i);
                });

                if (roomState == ROOM_STATE_ONGOING) {
                    this.throwTurn(uid2position[reconnectData['turn_uid']]);
                    this.enableChuPai();
                }
                else if (roomState == ROOM_STATE_ENDED) {
                    if (reconnectData.players) {
                        for (var i = 0; i < reconnectData.players.length; i++) {
                            var playerPai = reconnectData.players[i];
                            var isReady = !!playerPai['ready'];
                            if (isReady)
                                that.setReady(playerPai['uid']);
                        }
                    }
                }
            }
            else if (isInitPai) {
                forRows(function (i) {
                    this.recalcPos(i);
                });
            }
            gameData.huTipData = null;
            // for (var i = 0; i < 4; i++)
            //     if (i != 0)
            //         for (var j = 1; j <= 25; j++)
            //             this.addUsedPai(i, j);
        },

        /**
         * 检测红中是否可出
         * @param {Number} pai_id
         * @private
         * */
        _checkChuPai: function (pai_id) {
            // if (pai_id !== 32) {
            //     return true;
            // }

            // var array = this.getPaiArr();
            // var cansend = false;
            // for (var i = 0; i < array.length; i++) {
            //     var id = array[i];
            //     for (var key in g_ting_data) {
            //         if(key==gameData.uid)continue;
            //         var arr = g_ting_data[key];
            //         if (arr.indexOf(id) < 0) {
            //             cansend=true;
            //         }
            //     }
            // }
            // if(!cansend){//手里没有牌能出了 直接让出牌
            //     return true;
            // }
            pai_id = parseInt(pai_id)
            for (var key in g_ting_data) {
                if (key == gameData.uid)continue;
                var arr = g_ting_data[key];
                if (arr.indexOf(pai_id) >= 0) {
                    return false
                }
            }

            return true;
        },

        sendChuPai: function (row, idx, paiId) {
            this.clearTableAllSamePai();
            cc.log(row, idx, paiId);
            network.stop([3008, 4002, 4020, 4990, 3007, 4109]);
            if (this._checkChuPai(paiId)) {
                if (baijiaoStep == 2) {
                    network.send(4109, {room_id: gameData.roomId, pai_id: paiId, idx: idx, baiPaiArr:baijiaoArr || []});
                } else if (tiantingOpt) {
                    //TODO 天听
                    network.start();
                    this.sendChiPengGang(OP_TING, 2, paiId);
                    tiantingOpt = false;
                } else {
                    network.recv({
                        "code": 4002, "data": {
                            "room_id": gameData.roomId,
                            "uid": position2uid[row],
                            "pai_id": paiId,
                            "pai_arr": removeObjArray(this.getPaiArr(), paiId),//[18,24,22,14,18,17,15,24,26,25,11,27,27],
                            "idx": idx,
                            'fake': true
                        }
                    });
                    network.send(4002, {room_id: gameData.roomId, pai_id: paiId, idx: idx});
                    this.hideChiPengGangHu();
                }
                hasChupai = true;
            } else {
                this.downPai(2, idx);
                this.recalcPos(2);
                hasChupai = false;
                network.start();
                showMessageBox("其他玩家的听牌不可以打出")
                // alert1('手里有其它牌时,不能出王牌');
            }
        },
        resetSelfPaisState: function () {
            for (var i = 0; i < 14; i++) {
                var pai = this.getPai(2, i);
                if (pai) {
                    var userData = pai.getUserData()
                    pai.getUserData().isLiang = true;
                    Filter.remove(pai);
                    var jin = pai.getChildByName('jin')
                    if (jin) {
                        jin.setVisible(false)
                    }
                    var bai = pai.getChildByName('bai')
                    if (bai) {
                        bai.setVisible(false)
                    }
                    this.downPaiNow(2, i);
                }
            }
        },
        chuPai: function (row, idx, paiId, paiArr, baiPaiArr, fakeChu) {
            var that = this;

            if(row==2){
                this.hideTishiTip()
            }
            if (row != 2 && !isReplay)
                idx = 13;

            //this.playEffect('vCardOut');
            if (!fakeChu) {
                this.scheduleOnce(function () {
                    cc.log("出牌结束");
                    network.start()
                }, row == 2 ? 0.5 : 0.1)
            }

            var duration = 0.25;
            var usedPai = this.addUsedPai(row, paiId, fakeChu);


            that.setPaiArrOfRow(row, paiArr, (row != 2), (row != 2), undefined, baiPaiArr);

            if (row == 2) {
                that.recalcPos(row);
                that.upPai(row, -1);
                that.showArrow(usedPai, row);

                that.checkPaiAmount();
            }
            else {
                that.recalcPos(row);
                that.showArrow(usedPai, row);
            }

            usedPai.runAction(cc.fadeIn(duration));

            if (!fakeChu) {
                playEffect('vp' + paiId, position2sex[row]);
            }

        },
        checkPaiPos: function (row) {
            for (var j = 0; j < 14; j++) {
                var pai = this.getPai(row, j);
                var userData = pai.getUserData();
                //pai.setPositionX(posConf.paiPos[2][j].x);
                //console.log(j + '  ' + userData.isUp);
                if (!userData.isUpping && !userData.isDowning)
                    pai.setPosition(posConf.paiPos[2][j].x, (userData.isUp
                        ? posConf.upPaiPositionY
                        : posConf.downPaiPositionY));
            }
        },
        upPai: function (row, idx) {
            var that = this;
            this.checkPaiPos(row);
            if (idx >= 0 && baijiaoStep == 1) {
                var pai = that.getPai(row, idx);
                var userData = pai.getUserData();
                if (userData.isUp && !userData.isDowning) {
                    userData.isDowning = true;
                    pai.runAction(cc.sequence(
                        cc.moveTo(0.1, pai.getPositionX(), (!userData.isUp
                            ? posConf.upPaiPositionY
                            : posConf.downPaiPositionY))
                        , cc.callFunc(function () {
                            userData.isUp = false;
                            userData.isDowning = false;
                        })
                    ));
                }
                else if (!userData.isUpping) {
                    userData.isUpping = true;
                    pai.runAction(cc.sequence(
                        cc.moveTo(0.1, pai.getPositionX(), (!userData.isUp
                            ? posConf.upPaiPositionY
                            : posConf.downPaiPositionY))
                        , cc.callFunc(function () {
                            userData.isUp = true;
                            userData.isUpping = false;
                        })
                    ));
                }
                if (that.baijiaoLayer) {
                    that.baijiaoLayer.refreshChooseUpPais(that.getUpPaiArr())
                }
                return;
            }
            for (var i = 0; i < 14; i++) {
                (function (j) {
                    var pai = that.getPai(row, j);
                    var userData = pai.getUserData();
                    if (idx == j && userData.isUp) {
                        that.sendChuPai(row, idx, userData.pai);
                        userData.isUp = false;
                    }
                    else if (idx == j && !userData.isUp && !userData.isUpping) {
                        userData.isUpping = true;
                        pai.runAction(cc.sequence(
                            cc.moveTo(0.1, pai.getPositionX(), (!userData.isUp
                                ? posConf.upPaiPositionY
                                : posConf.downPaiPositionY))
                            , cc.callFunc(function () {
                                userData.isUp = true;
                                userData.isUpping = false;
                            })
                        ));
                    }
                    else if (idx != j && userData.isUp && !userData.isDowning) {
                        userData.isDowning = true;
                        pai.runAction(cc.sequence(
                            cc.moveTo(0.1, pai.getPositionX(), (!userData.isUp
                                ? posConf.upPaiPositionY
                                : posConf.downPaiPositionY))
                            , cc.callFunc(function () {
                                userData.isUp = false;
                                userData.isDowning = false;
                            })
                        ));
                    }
                })(i);
            }
        },
        downPaiNow: function (row, idx) {
            var that = this;
            this.checkPaiPos(row);
            var pai = that.getPai(row, idx);
            var userData = pai.getUserData();
            userData.isUp = false;
            userData.isDowning = false;
            userData.isUpping = false;
            pai.stopAllActions();
            pai.y = posConf.downPaiPositionY;
            // pai.runAction(cc.sequence(
            //     cc.moveTo(0.1, pai.getPositionX(), (!userData.isUp
            //         ? posConf.upPaiPositionY
            //         : posConf.downPaiPositionY))
            //     , cc.callFunc(function () {
            //         userData.isUp = false;
            //         userData.isDowning = false;
            //     })
            // ));
        },
        downPai: function (row, idx) {
            var that = this;
            this.checkPaiPos(row);
            var pai = that.getPai(row, idx);
            var userData = pai.getUserData();
            if (!userData.isUp || userData.isDowning)
                return;
            userData.isDowning = true;
            pai.runAction(cc.sequence(
                cc.moveTo(0.1, pai.getPositionX(), (!userData.isUp
                    ? posConf.upPaiPositionY
                    : posConf.downPaiPositionY))
                , cc.callFunc(function () {
                    userData.isUp = false;
                    userData.isDowning = false;
                })
            ));
        },
        enableChuPai: function () {
            if (enableChupaiCnt > 0)
                return;
            enableChupaiCnt++;

            var that = this;

            var curPaiIdx = -1;
            var beganTime, beganPosition;
            var isUp, paiIdx, paiId;
            var positionBak;
            var safeY;
            var toNodeDelta = {};
            var chupaiListener = cc.EventListener.create({
                event: cc.EventListener.TOUCH_ONE_BY_ONE,
                swallowTouches: true,
                onTouchBegan: function (touch, event) {
                    if (hasChupai || !that.isMyTurn() || disableChupai || roomState != ROOM_STATE_ONGOING)
                        return false;
                    var pai, _curPaiIdx = -1;
                    for (var i = 0; i < 14; i++) {
                        pai = that.getPai(2, i);
                        var userData = pai.getUserData();
                        if (!pai.isVisible())
                            continue;
                        if (TouchUtil.isTouchMe(pai, touch, event, null)) {
                            _curPaiIdx = i;
                            break;
                        }
                    }


                    if ((curPaiIdx >= 0 && _curPaiIdx != curPaiIdx)
                        || !(pai.getNumberOfRunningActions() == 0 || !pai.getUserData().isUpping && !pai.getUserData().isDowning)
                        || pai.getUserData().isLiang === false)
                        return false;

                    curPaiIdx = _curPaiIdx;

                    if (curPaiIdx >= 0) {
                        var userData = pai.getUserData();
                        for (var k = 0; k < 14; k++)
                            if (that.getPai(2, k).getNumberOfRunningActions() > 0)
                                return false;
                        if (gameData.huTipData) {
                            that.showTishiTip(gameData.huTipData);
                            // console.log("333");
                        }
                        that.playEffect('vCardClick');

                        beganTime = getCurrentTimeMills();

                        // back up
                        userData.positionBak = pai.getPosition();
                        userData.scaleBak = pai.getScaleX();

                        isUp = userData.isUp;
                        if (!isUp || baijiaoStep == 1)
                            that.upPai(2, userData.idx);
                        if (userData.hucards) {
                            var jiaoSp = pai.getChildByName('hucardSprite');
                            if (jiaoSp && jiaoSp.isVisible())
                                that.HuCardTip(userData.hucards, pai.getPositionX(), true);
                        }
                        paiIdx = userData.idx;
                        paiId = userData.pai;
                        positionBak = _.clone(posConf.paiPos[2][curPaiIdx]);
                        positionBak.y = (true || isUp
                            ? posConf.upPaiPositionY
                            : posConf.downPaiPositionY);
                        beganPosition = touch.getLocation();
                        safeY = pai.getBoundingBox().height;
                        var a = touch.getLocation();
                        var b = pai.convertToNodeSpace(touch.getLocation());
                        toNodeDelta.x = a.x - b.x;
                        toNodeDelta.y = a.y - b.y;

                        //点亮选中牌
                        that.showTableAllSamePai(paiId);
                    }

                    return curPaiIdx >= 0;
                },
                onTouchMoved: function (touch, event) {
                    if (curPaiIdx < 0)
                        return;
                    if (baijiaoStep == 1)
                        return;

                    var pai = that.getPai(2, curPaiIdx);
                    var userData = pai.getUserData();


                    if (beganPosition) {
                        var p = touch.getLocation();
                        p.x -= toNodeDelta.x;
                        p.y -= toNodeDelta.y;
                        if (p.y < safeY) {
                            if (pai.getNumberOfRunningActions() <= 0)
                                pai.setPosition(positionBak);
                            return;
                        }
                        p = pai.convertToNodeSpace(touch.getLocation());
                        p.x += pai.getPositionX() - pai.getBoundingBox().width / 2;
                        p.y += pai.getPositionY() - pai.getBoundingBox().height / 2;
                        //that.setPai(2, 15, userData.pai);
                        pai.setPosition(p);
                    }
                },
                onTouchEnded: function (touch, event) {
                    that.HuCardTip(null, null, false);
                    if (curPaiIdx < 0)
                        return;

                    var pai = that.getPai(2, curPaiIdx);
                    var userData = pai.getUserData();

                    if (beganPosition) {
                        var p = touch.getLocation();
                        p.x -= toNodeDelta.x;
                        p.y -= toNodeDelta.y;
                        var now = getCurrentTimeMills();
                        var isSend = (p.y < safeY && isUp && Math.abs(now - beganTime) < 168) || (p.y > safeY);
                        if (isSend) {
                            if (baijiaoStep != 1) {
                                that.sendChuPai(2, paiIdx, paiId);
                                that.setHuTipVisible(false);
                            }
                        }
                        else {
                            that.checkPaiPos(2);
                            that.scheduleOnce(function () {
                                curPaiIdx = -1;
                                beganPosition = null;
                            }, UPDOWNPAI_ANIM_DURATION);
                        }
                    }
                    curPaiIdx = -1;
                    beganPosition = null;
                    return false;
                }
            });
            that.HuCardTip(null, null, false);
            return cc.eventManager.addListener(chupaiListener, $('row2'));
        },
        clearTableAllSamePai:function () {
            for(var i=0; i<4; i++){
                var chuNode = $('row'+i+".c0");
                var chuNodes = chuNode.getChildren();
                for(var j=0; j<chuNodes.length; j++){
                    var pai = chuNodes[j];
                    pai.setColor(cc.color(255,255,255));
                }
                for(var j=0; j<14; j++){
                    var pai = this.getPai(i, j)
                    pai.setColor(cc.color(255,255,255));
                }
                for(var j=0; j<4; j++){
                    for(var z=0; z<4; z++){
                        var tp = this.getGPai(i, j, z);
                        if(tp){
                            tp.setColor(cc.color(255,255,255));
                        }
                    }
                }
            }
        },
        showTableAllSamePai : function (id) {
            this.clearTableAllSamePai();
            for(var i=0; i<4; i++){
                var chuNode = $('row'+i+".c0");
                var chuNodes = chuNode.getChildren();
                for(var j=0; j<chuNodes.length; j++){
                    var pai = chuNodes[j];
                    var udata = pai.getUserData()
                    if(udata && udata.pai == id){
                        pai.setColor(cc.color(255,150,150));
                    }
                }
                for(var j=0; j<14; j++){
                    if(i==2)break;
                    var pai = this.getPai(i, j)
                    var udata = pai.getUserData()
                    if(pai.isVisible() && udata && udata.pai == id){
                        pai.setColor(cc.color(255,150,150));
                    }
                }
                for(var j=0; j<4; j++){
                    var pai = this.getGPai(i, j, 0)
                    var udata = pai.getUserData()
                    if(pai.isVisible() && udata && udata.pai == id){
                        //pai.setColor(cc.color(255,125,125));
                        for(var z=0; z<4; z++){
                            var tp = this.getGPai(i, j, z);
                            if(tp){
                                tp.setColor(cc.color(255,150,150));
                            }
                        }
                    }
                }
            }
        },
        countDown: function () {
            var that = this;
            var timer = null;
            return function (seconds) {
                if (isReplay) {
                    $('timer.sec').setString('');
                    return;
                }
                if (timer) {
                    clearInterval(timer);
                    timer = null;
                }
                $('timer.sec').setString(seconds);
                $('timer.sec').setVisible(true);
                timer = setInterval(function () {
                    var sec;
                    sec = $('timer.sec');
                    if (!cc.sys.isObjectValid(sec)) {
                        if (timer)
                            clearInterval(timer);
                        return;
                    }
                    if (!sec) {
                        clearInterval(timer);
                        timer = null;
                        return;
                    }
                    if (seconds > 0) {
                        --seconds;
                        sec.setString(seconds < 10 ? "0" + seconds : seconds);
                    }
                    if (seconds == 0) {
                        if (turnRow == 2 && !hasChupai)
                            DeviceUtil.vibrate();
                        clearInterval(timer);
                    }
                }, 1000);
            }
        },
        closePai: function (paiId) {

        },
        setPaiArrOfRow: function (row, paiArr, isLittle, isStand, huPaiId, baipaiArr, insertHupaiid) {
            //如果存在摆拍 删除并且放置于合适位置
            var tempPaiArr = deepCopy(paiArr);
            baipaiArr = baipaiArr || []
            if (baipaiArr.length > 0) {
                for (var i = 0; i < baipaiArr.length; i++) {
                    var bai = baipaiArr[i];
                    var idx = tempPaiArr.indexOf(bai);
                    if (idx >= 0) {
                        tempPaiArr.splice(idx, 1);
                    } else {
                        cc.log("找不到摆拍--》》》", bai);
                        tempPaiArr.splice(idx, 1);
                    }
                }
            }

            paiArr = this.sortPaiArr(tempPaiArr, row);
            paiArr = this._sort(paiArr);
            var baiIdxStart = paiArr.length;
            var baiIdxEnd = baiIdxStart + baipaiArr.length;
            paiArr = paiArr.concat(baipaiArr)

            if (huPaiId) {
                var idx = paiArr.indexOf(huPaiId);
                if (idx >= 0) {
                    paiArr.splice(idx, 1);
                    //paiArr.push(huPaiId);
                    baiIdxStart -= 1;
                    baiIdxEnd -= 1;
                }
            }
            // else if(insertHupaiid){
            //     paiArr.push(insertHupaiid);
            // }

            var lastPai = null;
            for (var j = 0; j < paiArr.length; j++) {
                lastPai = this.setPai(row, j, paiArr[j], isLittle, isStand, true);
                // cc.log("setPaiArrOfRow -> ", j, paiArr[j]);
                lastPai.stopAllActions();
                lastPai.setOpacity(255);
                var baiIcon = lastPai.getChildByName('bai')
                if (j >= baiIdxStart && j < baiIdxEnd) {//摆拍添加标识
                    if (!baiIcon) {
                        baiIcon = new cc.Sprite(majiang_gs.res['bai_png_' + row]);
                        // sp.setPosition(cpg.getChildByName('sp_' + i).getPosition());
                        baiIcon.setName('bai');
                        lastPai.addChild(baiIcon);
                    }
                    baiIcon.setVisible(true)
                    if (row == 2) {
                        baiIcon.x = lastPai.width / 2;
                        baiIcon.y = lastPai.height + baiIcon.height / 2 - 5;
                    } else if (row == 0) {
                        baiIcon.x = lastPai.width / 2;
                        baiIcon.y = -baiIcon.height / 2;
                    } else if (row == 1) {
                        baiIcon.x = -baiIcon.width / 2;
                        baiIcon.y = lastPai.height / 2
                    } else if (row == 3) {
                        baiIcon.x = baiIcon.width / 2 + lastPai.width;
                        baiIcon.y = lastPai.height / 2
                    }
                } else {
                    if (baiIcon) {
                        baiIcon.setVisible(false)
                    }
                    if (row == 2) {
                        this.checkPaiJinIcon(lastPai, paiArr[j])

                    }
                }
            }
            for (; j < 14; j++)
                this.setPai(row, j, 0, isLittle, isStand, false);

            huPaiId = huPaiId || insertHupaiid
            if (huPaiId && cc.sys.isObjectValid(lastPai)) {
                // lastPai.setOpacity(168);
                lastPai = this.setPai(row, 13, huPaiId, isLittle, isStand, true);
                lastPai.stopAllActions();
                lastPai.setOpacity(255);
                this.recalcPos(row);
            }
        },
        checkPaiJinIcon: function (pai, id) {
            var jinIcon = pai.getChildByName('jin')
            //判断是否禁牌
            if (!this._checkChuPai(id)) {
                if (!jinIcon) {
                    jinIcon = new cc.Sprite(majiang_gs.res['jin_png']);
                    // sp.setPosition(cpg.getChildByName('sp_' + i).getPosition());
                    jinIcon.setName('jin');
                    pai.addChild(jinIcon);
                }
                jinIcon.setVisible(true);
                jinIcon.x = pai.width - jinIcon.width + 10;
                jinIcon.y = pai.height - jinIcon.height;
            } else {
                if (jinIcon) jinIcon.setVisible(false);
            }
        },

        /**
         * 牌排序
         * @param {Array} pai_arr
         * @param {Array} [exclude_arr]
         * @private
         * */
        _sort: function (pai_arr, exclude_arr) {
            exclude_arr = exclude_arr || [];
            var arr = deepCopy(pai_arr);
            for (var i = 0; i < exclude_arr.length; i++) {
                _.pull(arr, exclude_arr[i]);
            }
            arr.sort(function (a, b) {
                return a - b;
            });
            cc.log('手牌数组：' + arr);
            return arr;
        },

        sortFront: function (paiArr, id) {
            var oldSize = paiArr.length;
            _.pull(paiArr, id);
            if (paiArr.length != oldSize) {
                var t = paiArr.length;
                for (var j = 0; j < oldSize - t; j++)
                    paiArr.splice(0, 0, id);
            }
        },
        checkMyPaiColor4SC: function (allShowCards) {
            cc.log("checkMyPaiColor4SC  " + allShowCards);
            // baijiaoObj = baijiaoObj || {}
            // var allShowCards = []
            // for (var key in baijiaoObj) {
            //     var cardsObj = baijiaoObj[key];
            //     for (var _key in cardsObj) {
            //         var cards = cardsObj[_key]
            //         for (var i = 0; i < cards.length; i++) {
            //             if (allShowCards.indexOf(cards[i]) < 0) {
            //                 allShowCards.push(cards[i])
            //             }
            //         }
            //     }
            // }

            var paiArr = this.getPaiArr();

            for (var j = 0; j < paiArr.length; j++) {
                var paiId = paiArr[j];
                this.filterMyPai(2, j, allShowCards.indexOf(paiId) >= 0 ? 1 : 0);
            }
            var pai13Id = paiArr[paiArr.length - 1]
            if (pai13Id) {
                this.filterMyPai(2, 13, allShowCards.indexOf(pai13Id) >= 0 ? 1 : 0);
            }
        },
        filterMyPai: function (row, idx, val) {
            // cc.log(row, idx, val)
            var that = this;
            var pai = this.getPai(row, idx);
            if (val == -1) {
                pai.getUserData().isLiang = true;
                Filter.grayScale(pai);
            }
            if (val == 0 && !that.isReplay) {
                pai.getUserData().isLiang = false;
                Filter.grayMask(pai);
            }
            if (val == 1) {
                pai.getUserData().isLiang = true;
                Filter.remove(pai);
            }
        },
        refreshSelfPaiArr: function () {
            var paiArr = this.getPaiArr()
            // this.setPaiArrOfRow(2, paiArr, false, false);

            for (var j = 0; j < paiArr.length; j++) {
                var paiId = paiArr[j];
                var pai = this.getPai(2, j, paiArr[j]);
                pai.setOpacity(255);
                this.filterMyPai(2, j, 1);
                var userData = pai.getUserData();
                userData.isUp = false;
                userData.isUpping = false;
                userData.isDowning = false;
            }
            var pai = this.getPai(2, 13);
            if (pai && pai.isVisible()) {
                this.filterMyPai(2, 13, 1);
                var userData = pai.getUserData();
                userData.isUp = false;
                userData.isUpping = false;
                userData.isDowning = false;
            }
            this.recalcPos(2)
        },
        mopai: function (row, paiId, paiArr, baipaiArr) {
            if (row == 2) {
                hasChupai = false;
                this.setPaiArrOfRow(2, paiArr, false, false, undefined, baipaiArr);
            }

            var that = this;
            //动画
            var func = function () {


                that.throwTurn(row);

                if (row == 2) {
                    that.recalcPos(2);
                }


                that.countDown(12);
            };

            if (row == 2) {
                network.stop([3008, 4020]);

                this.setPai(row, 13, (row == 2 || isReplay ? paiId : 0), (row != 2), (row != 2), true)
                this.getPai(row, 13).setOpacity(255);


                this.scheduleOnce(function () {
                    network.start();
                    func();
                }, 0.1)

                if (row == 2)
                    this.checkPaiJinIcon(this.getPai(row, 13), paiId)
            } else {
                //摆拍显示
                // var len = that.getPaiCoutOfRow(row) - 1
                //
                // for (var i = 0; i < baipaiArr.length; i++) {
                //     var id = baipaiArr[i];
                //     this.setPai(row, len - i - 1, id, true, false, true)
                // }


                this.setPai(row, 13, (row == 2 || isReplay
                    ? paiId
                    : 0), (row != 2), (row != 2), true)
                    .runAction(cc.fadeIn(MOPAI_ANIM_DURATION));


                func();
            }
        },
        showChiPengGangHu: function (row, paiId, chi, peng, gang, hu, ting, data) {
            var that = this;

            if (!isReplay) {
                var _opPaiIdArr = {};

                var children = $('cpghg').getChildren();
                for (var i = 0; i < children.length; i++) {
                    children[i].setVisible(false);
                }

                var sum = (chi || 0) + (peng || 0) + (gang || 0) + (hu || 0) + (ting || 0) + 1;

                $('cpghg.chi').setVisible(false);
                $('cpghg.peng').setVisible(false);
                $('cpghg.gang').setVisible(false);
                $('cpghg.hu').setVisible(false);
                $('cpghg.ting').setVisible(false);
                var nodeArr = [], opArr = [];
                if (chi) {
                    nodeArr.push($('cpghg.chi'));
                    opArr.push(OP_CHI);
                }

                if (peng) {
                    nodeArr.push($('cpghg.peng'));
                    opArr.push(OP_PENG);
                }
                if (gang) {
                    nodeArr.push($('cpghg.gang'));
                    opArr.push(OP_GANG);
                }
                if (hu) {
                    nodeArr.push($('cpghg.hu'));
                    opArr.push(OP_HU);
                }
                if (ting) {
                    nodeArr.push($('cpghg.ting'));
                    opArr.push(OP_TING);
                }
                nodeArr.push($('cpghg.guo'));

                for (var i = 0; i < nodeArr.length; i++) {
                    if (i < nodeArr.length - 1) {
                        var node = $('a', nodeArr[i]);
                        if (!node) {
                            var node = duplicateNode($('row2.c0.b0'));
                            node.setName('a');
                            node.setPosition($('n', nodeArr[i]).getPosition());
                            node.setVisible(true);
                            nodeArr[i].addChild(node);
                        }
                        var _paiId = _opPaiIdArr[opArr[i]] || paiId;
                        var paiName = getPaiNameByRowAndId(2, _paiId, true);
                        setSpriteFrameByName(node, paiName, majiang_gs.res.pai0plist);
                        node.setUserData({paiId: _paiId});
                    }

                    if (typeof posConf.cpghgPositionX[sum][i] === 'number')
                        nodeArr[i].setPositionX(posConf.cpghgPositionX[sum][i]);
                    else
                        nodeArr[i].setPosition(posConf.cpghgPositionX[sum][i]);
                    nodeArr[i].setVisible(true);
                }


                chi && TouchUtil.setOnclickListener($('cpghg.chi'), function () {
                    var _paiId = $('cpghg.chi.a').getUserData().paiId || paiId;
                    that.showChiLayer(_paiId, function (paiId, oriPaiId) {
                        that.sendChiPengGang(OP_CHI, 2, paiId, oriPaiId);
                    });
                });

                peng && TouchUtil.setOnclickListener($('cpghg.peng'), function () {
                    var _paiId = $('cpghg.peng.a').getUserData().paiId || paiId;
                    that.sendChiPengGang(OP_PENG, 2, _paiId);
                    that.hideChiPengGangHu();
                });

                ting && TouchUtil.setOnclickListener($('cpghg.ting'), function () {
                    var _paiId = $('cpghg.ting.a').getUserData().paiId || paiId;

                });

                hu && TouchUtil.setOnclickListener($('cpghg.hu'), function () {
                    var _paiId = $('cpghg.hu.a').getUserData().paiId || paiId;
                    do {

                        that.sendChiPengGang(OP_HU, 2, _paiId);
                        that.hideChiPengGangHu();
                    } while (false);
                });

                gang && TouchUtil.setOnclickListener($('cpghg.gang'), function () {
                    var _paiId = $('cpghg.gang.a').getUserData().paiId || paiId;
                    that.sendChiPengGang(OP_GANG, 2, _paiId);
                    that.hideChiPengGangHu();
                });

                TouchUtil.setOnclickListener($('cpghg.guo'), function () {
                    if (hu && that.isMyTurn()) {
                        that.sendChiPengGang(OP_PASS, 2, paiId);
                        that.hideChiPengGangHu();
                    }
                    else {
                        that.sendChiPengGang(OP_PASS, 2, paiId);
                        that.hideChiPengGangHu();
                    }
                });

                $('cpghg').setVisible(true);

                this.countDown(12);
            } else {
                // var cpg = $('cpghRep' + row);
                // for (var i = 0; i < 6; i++) {
                //     if (!cpg.getChildByName('sp1_' + i)) {
                //         var sp = new cc.Sprite(majiang_gs.res['sp1_' + i + '_png']);
                //         sp.setPosition(cpg.getChildByName('sp_' + i).getPosition());
                //         sp.setName('sp1_' + i);
                //         cpg.addChild(sp);
                //         sp.setVisible(false);
                //     }
                // }
                // $('cpghRep' + row + '.sp1_0').setVisible(!!chi);
                // $('cpghRep' + row + '.sp1_1').setVisible(!!peng);
                // $('cpghRep' + row + '.sp1_2').setVisible(!!gang);
                // $('cpghRep' + row + '.sp1_3').setVisible(!!hu);
                // $('cpghRep' + row + '.sp1_4').setVisible(true);
                // $('cpghRep' + row + '.sp1_5').setVisible(false);
                //
                // $('cpghRep' + row + '.sp_0').setVisible(!chi);
                // $('cpghRep' + row + '.sp_1').setVisible(!peng);
                // $('cpghRep' + row + '.sp_2').setVisible(!gang);
                // $('cpghRep' + row + '.sp_3').setVisible(!hu);
                // $('cpghRep' + row + '.sp_4').setVisible(false);
                // $('cpghRep' + row + '.sp_5').setVisible(true);
                //
                // var pai = $('cpghRep' + row + '.sp_pai');
                // var paiName = getPaiNameByRowAndId(2, paiId, true);
                // pai.setScale(0.65, 0.65);
                // setSpriteFrameByName(pai, paiName, majiang_gs.res.pai0plist);
                // cpg.setVisible(true);
            }
        },
        hideChiPengGangHu: function () {
            $('cpghg').setVisible(false);
            if ($('chiLayer'))
                $('chiLayer').removeFromParent(false);
        },
        sendChiPengGang: function (op, row, paiId, oriPaiId) {
            network.send(4003, {room_id: gameData.roomId, op: op, pai_id: paiId, ori_pai_id: oriPaiId});
        },

        /**
         * 胡牌动画
         * @private
         * */
        _huAnimation: function (row, hu_type) {
            var ani_json = '';
            switch (hu_type) {
                case majiang.HuType.ZiMo:
                    ani_json = majiang_gs.res.ZIMO_json;
                    playEffect('vzimo', position2sex[row]);
                    break;
                default:
                    break;
            }
            network.stop();
            if (ani_json !== '') {
                var infoNode = $('info_n' + row);
                infoNode.removeAllChildren();
                playAnimScene(infoNode, ani_json, 0, 0, false, function () {
                    infoNode.removeAllChildren();
                });
                this.scheduleOnce(function () {
                    network.start();
                }, 2);
            } else {
                network.start();
            }
        },

        playChiPengGangHuAnim: function (row, op, is_zimo) {
            var ccsname = is_zimo ? 'ZIMO_json' : {
                    1: 'CHI_json',
                    2: 'PENG_json',
                    3: 'GANG_json',
                    4: 'HU_json',
                    6: 'TING_json',
                    99: "BAI_json"
                }[op];

            var infoNode = $('info_n' + row);
            if (infoNode.children.length != 0) {
                infoNode.removeAllChildren();
            }

            playAnimScene(infoNode, res[ccsname], 0, 0, false, function () {
                infoNode.removeAllChildren();
            });
        },
        setReplayProgress: function (cur, total) {
            var progress = cur / total * 100;
            this.showTip('回放进度: ' + progress.toFixed(1) + '%', false);
        },
        setAllPai4Replay: function (data) {
            for (var uid in data)
                if (data.hasOwnProperty(uid)) {
                    var row = uid2position[uid];
                    var paiArr = data[uid]['pai_arr'];
                    this.setPaiArrOfRow(row, paiArr, (row != 2), false);

                    var duiArr = data[uid]['dui_arr'];
                    for (var j = 0; j < duiArr.length; j++) {
                        var dui = duiArr[j];
                        var fromRow = uid2position[dui['from_uid']];
                        if (dui.type == 1) this.setGChi(row, j, dui['pai_arr']);
                        if (dui.type == 2) this.setGPeng(row, j, dui['pai_arr'][0], fromRow);
                        if (dui.type == 3) this.setGGang(row, j, dui['pai_arr'][0], dui['pai_arr'][0], fromRow);
                        if (dui.type == 4) this.setGGang(row, j, dui['pai_arr'][0], 0, fromRow);
                        if (dui.type == 5) this.setGHide(row, j);
                    }
                    for (; j < 4 && $('row' + row + '.g' + j); j++)
                        $('row' + row + '.g' + j).setVisible(false);

                    if ($('row' + row + '.g' + 0).isVisible() == 0) {
                        $('row' + row + '.a' + 0).setPosition(posConf.paiA0PosBak[row]);
                    }

                    var usedArr = data[uid]['used_arr'];
                    for (var j = 0; j < 24; j++) {
                        var pai = $('row' + row + '.c0.b' + j);
                        if (pai)
                            pai.setVisible(false);
                        else
                            break;
                    }
                    for (var j = 0; j < usedArr.length; j++) {
                        this.addUsedPai(row, usedArr[j]);
                    }

                    this.recalcPos(row);
                }
        },
        chiPengGangHu: function (op, row, paiId, fromRow, data) {

            if (isReplay) {
                var node = $('cpghRep' + row + '.sp_' + (op - 1));

                var touch_node = new cc.Node();
                $('cpghRep' + row).addChild(touch_node);
                touch_node.setPosition(node.getPositionX(), node.getPositionY() - 40);

                var touch_sp0 = new cc.Sprite(res.touch0);
                var touch_sp1 = new cc.Sprite(res.touch1);
                touch_node.addChild(touch_sp0);
                touch_node.addChild(touch_sp1);
                touch_sp1.setVisible(false);

                touch_node.runAction(cc.sequence(cc.delayTime(0.5), cc.callFunc(function () {
                    touch_sp0.setVisible(false);
                    touch_sp1.setVisible(true);
                }), cc.delayTime(0.818), cc.callFunc(function () {
                    touch_node.removeFromParent();
                    $('cpghRep' + row).setVisible(false);
                })));
            }

            var j;
            for (j = 0; j < 4; j++) {
                var g = $('row' + row + '.g' + j);
                if (!g || !$('row' + row + '.g' + j).isVisible())
                    break;
            }

            var paiArr = this.getPaiArr();

            if (op == OP_CHI) {
                var oriPaiId = data['ori_pai_id'];
                this.setGChi(row, j, paiId, oriPaiId);
                hasChupai = false;
                this.removeOneTopUsedPai(fromRow);
                this.playChiPengGangHuAnim(row, op);
                playEffect('vchi', position2sex[row]);
            } else if (op == OP_PENG || op == OP_GANG) {
                var duiArr = (data['dui_arr'] || []);
                var isJiagang = (data['is_jiagang'] || 0);

                if (op == OP_PENG) {
                    this.setGPeng(row, j, paiId, fromRow);
                    _.remove(paiArr, function (n) {
                        return n == paiId;
                    });
                    hasChupai = false;
                    this.removeOneTopUsedPai(fromRow);
                    this.playChiPengGangHuAnim(row, op);
                    playEffect('vpeng', position2sex[row]);
                }
                else if (op == OP_PENG || op == OP_GANG) {
                    var isAngang = (row == fromRow && !isJiagang);
                    var upPaiId = paiId;
                    var downPaiId = (isAngang
                        ? 0
                        : paiId);

                    if (duiArr)
                        this.setDuiArr(row, duiArr);
                    else {
                        if (isAngang || !isJiagang) {   // angang or minggang
                            this.setGGang(row, j, upPaiId, downPaiId, fromRow);
                        }
                        else if (isJiagang) {
                            this.setGJiaGang(row, paiId, fromRow);
                        }
                    }

                    if (row != fromRow)
                        this.removeOneTopUsedPai(fromRow);

                    _.remove(paiArr, function (n) {
                        return n == paiId;
                    });

                    hasChupai = false;
                    if (row == 2 || isJiagang)
                        hasChupai = true;

                    this.playChiPengGangHuAnim(row, op, false, isAngang);
                    playEffect(isAngang
                        ? 'vangang'
                        : 'vgang', position2sex[row]);
                }

                this.hideChiPengGangHu();

                if (!isJiagang && !duiArr)
                    $('row' + row + '.g' + j).setVisible(true);
            }
            else if (op == OP_HU) {
                var hu_type = data['hu_type'];
                var is_zimo = (hu_type === majiang.HuType.ZiMo);
                if (fromRow == 2) {
                    this.hideChiPengGangHu();
                }
                if (!is_zimo) {
                    this.removeOneTopUsedPai(fromRow, paiId);
                }
                this.playChiPengGangHuAnim(row, op, is_zimo);
                // this._huAnimation(row, hu_type);
                playEffect(is_zimo ? 'vzimo' : 'vhu', position2sex[row]);
            } else {
                return;
            }

            this.playerOnloneStatusChange(row, false);

            var _paiArr = (data['pai_arr'] || []);
            var paiCnt = (data['pai_cnt'] || 0);
            var n = paiCnt - _paiArr.length;
            for (var i = 0; i < n; i++)
                _paiArr.push(0);
            if (op == OP_HU) {
                curHuPaiId = paiId;
                playerHuPaiId[row] = paiId;
            }
            if (op !== OP_HU) {
                this.setPaiArrOfRow(row, _paiArr, (row != 2), (op != OP_HU), playerHuPaiId[row]);
            }

            if (op == OP_HU && _.isObject(data['player'])) {
                var playerMap = data['player'];
                for (var uid in playerMap) {
                    var tRow = uid2position[uid];
                    var tPaiArr = playerMap[uid]['pai_arr'];
                    var tDuiArr = playerMap[uid]['dui_arr'];
                    if (tRow != 2) {
                        for (var i = 0; i < tPaiArr.length; i++)
                            tPaiArr[i] = 0;
                    }
                    this.setDuiArr(tRow, tDuiArr);
                    this.setPaiArrOfRow(tRow, tPaiArr, (tRow != 2), (tRow != 2), playerHuPaiId[tRow]);
                    this.recalcPos(tRow);
                }
            } else if (op == OP_HU) {
                //胡牌牌界面刷新
                if (row == 2) {
                    cc.log("-----111111");
                    this.setPaiArrOfRow(row, data['pai_arr'], (row != 2), (row != 2), data['pai_id'], data['bai_pai_arr']);
                } else {
                    var pai_cnt = data['pai_cnt'];
                    var count = pai_cnt - 1
                    var _paiArr = [];
                    for (var x = 0; x < count; x++) {
                        _paiArr.push(0)
                    }
                    //_paiArr.push(data['pai_id'])
                    this.setPaiArrOfRow(row, _paiArr, (row != 2), (row != 2), undefined, data['bai_pai_arr'], data['pai_id']);
                }

            }

            if (op != OP_HU) {
                this.setPai(row, 13, 0, undefined, undefined, false);
                // this.getPai(row, 13).runAction(cc.fadeOut(0));
            }

            this.recalcPos(row);

            this.checkPaiAmount();

        },

        fapai: function (paiArr) {
            paiArr = this._sort(paiArr, [0]);

            forRows(function (i) {
                for (var j = 0; j < paiArr.length; j++)
                    this.setPai(i, j, (i == 2
                        ? paiArr[j]
                        : 0), (i != 2), (i != 2));
                for (; j < 14; j++)
                    this.setPai(i, j, 0, (i != 2), (i != 2), false);
            });
            this.setPai(2, 13, 0, false, false, this.isMyTurn());
            forRows(function (i) {
                for (var j = 0; j < 13; j++) {
                    this.getPai(i, j).setVisible(true);
                    this.getPai(i, j).runAction(
                        cc.sequence(cc.delayTime(j * FAPAI_ANIM_DELAY), cc.fadeIn(FAPAI_ANIM_DURATION))
                    );
                    var userData = this.getPai(i, j).getUserData();
                    userData.isUp = false;
                    userData.isUpping = false;
                    userData.isDowning = false;
                }
                this.getPai(i, 13).setVisible(false);
                this.getPai(i, 13).getUserData().isUp = false;
                this.getPai(i, 13).isUp = false;
                this.getPai(i, 13).isUpping = false;
                this.getPai(i, 13).isDowning = false;
                this.recalcPos(i);
            });
            this.enableChuPai();

            if ($('info0.bai')) $('info0.bai').setVisible(false);
            if ($('info1.bai')) $('info1.bai').setVisible(false);
            if ($('info2.bai')) $('info2.bai').setVisible(false);
            if ($('info3.bai')) $('info3.bai').setVisible(false);

            curHuPaiId = 0;
            playerHuPaiId = {};
            this.HuCardTip(null, 0, false);
        },
        jiesuan: function (data) {
            var that = this;
            that.jieSuanData = data;
            var myScore = 0;
            var players = data.players;
            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                var uid = player['uid'];

                gameData.players[position2playerArrIdx[uid2position[uid]]].total_score = player['total_score'];
                $('info' + uid2position[uid] + '.lb_score').setString(player['total_score']);

                if (uid == gameData.uid) {
                    myScore = player['score'];
                    continue;
                }

                var row = uid2position[uid];
                var paiArr = player['pai_arr'];
                // if (data['hu_type'] == 2 && player['hu'])
                //     this.setPaiArrOfRow(uid2position[uid], paiArr, (row != 2), false, playerHuPaiId[row]);
                // else
                //     this.setPaiArrOfRow(uid2position[uid], paiArr, (row != 2), false);
                //this.recalcPos(row)
            }
        },

        /**
         * 打开结算
         * @private
         * */
        _openJiesuanLayer: function () {
            if (this._jiesuan_data) {
                var that = this;
                this.scheduleOnce(function () {
                    var is_winner = false;
                    var players = this._jiesuan_data.players || [];
                    for (var i = 0; i < players.length; i++) {
                        if (players[i] && players[i]['uid'] === gameData.uid) {
                            if (players[i]['score'] > 0) {
                                is_winner = true;
                                break;
                            }
                        }
                    }
                    if (mapId == app.map_id.GanSu_BaiJiao) {
                        this.addChild(new JiesuanLayer_lnbj(this._jiesuan_data));
                    } else {
                        this.addChild(new JiesuanLayer(this._jiesuan_data));
                    }
                    playEffect(is_winner
                        ? 'vWin'
                        : 'vLose');
                }, 2)
            }
        },
        onJiesuanClose: function (isReady) {
            if (isReplay)
                return;
            if (isReady) {
                $('btn_zhunbei').setVisible(false);
            } else {
                $('btn_zhunbei').setVisible(true);
            }
            if (zongjiesuanData && !isReady) {
                this.showZongJiesuan();
            }
        },
        zongJiesuan: function (data) {
            zongjiesuanData = data;
        },
        showZongJiesuan: function () {
            var that = this;
            var layer = new ZongJiesuanLayer(zongjiesuanData);
            that.addChild(layer, 2);
        },
        showPlayerInfoPanel: function (idx) {
            if (window.inReview || this.getRoomState() != ROOM_STATE_ONGOING || isReplay)
                return;

            if (position2playerArrIdx[idx] >= gameData.players.length)
                return;
            var that = this;
            var playerInfo = gameData.players[position2playerArrIdx[idx]];
            network.send(3018, {cmd: 'queryEmoji', uid: gameData.uid, room_id: gameData.roomId});
            showWindow('PlayerInfoInGameWindow', playerInfo, that);
        },
        playerOnloneStatusChange: function (row, isOffline) {
            if ($('info' + row + '.offline'))
                $('info' + row + '.offline').setVisible(!!isOffline);
        },

        setZhuang: function (row) {
            cc.log("setzhuang -> " + row)
            $('info0.zhuang').setVisible(false);
            $('info1.zhuang').setVisible(false);
            $('info2.zhuang').setVisible(false);
            $('info3.zhuang').setVisible(false);
            if ($('info' + row + '.zhuang'))
                $('info' + row + '.zhuang').setVisible(true);
        },
        setBeforeOnCCSLoadFinish: function (cb) {
            this.beforeOnCCSLoadFinish = cb;
        },
        getBeforeOnCCSLoadFinish: function (cb) {
            return this.beforeOnCCSLoadFinish;
        },
        setAfterGameStart: function (cb) {
            this.afterGameStart = cb;
        },
        setReady: function (uid) {
            cc.log("setReady --> ", uid);
            var ok = $('info' + uid2position[uid] + '.ok');
            if (ok)
                ok.setVisible(true);
            if (uid == gameData.uid && $('btn_zhunbei'))
                $('btn_zhunbei').setVisible(false);

            if (uid2playerInfo[uid]) {
                uid2playerInfo[uid]['ready'] = 1;
            }

        },
        showToast: function (msg) {
            var toast = $('toast');
            if (!toast) {
                toast = new cc.Sprite(res.toast_bg_png);
                toast.setName('toast');
                this.addChild(toast);

                var text = new ccui.Text();
                text.setName('text');
                text.setFontSize(30);
                text.setTextColor(cc.color(255, 255, 255));
                text.setPosition(toast.getBoundingBox().width / 2, toast.getBoundingBox().height / 2);
                text.setString(msg);
                toast.setPosition(cc.winSize.width / 2, cc.winSize.height / 2 * 4 / 5);
                toast.addChild(text);
            }
            toast.stopAllActions();
            toast.runAction(cc.sequence(cc.fadeIn(3), cc.fadeOut(0.3)));
            text = toast.getChildByName('text');
            text.runAction(cc.sequence(cc.fadeIn(3), cc.fadeOut(0.3)));
        },
        initWanfa: function () {
            if (!gameData.wanfaDesp)
                return;
            var arr = decodeURIComponent(gameData.wanfaDesp).split(',');
            var topPosY = cc.winSize.height / 2 + 116;

            var sp_wanfa_Pos = cc.p(0, topPosY);
            var sp_wanfa = new cc.Sprite(res.sp_wanfa_png);
            var sp_wanfa_size = cc.size(47, 85);
            sp_wanfa.setPosition(sp_wanfa_Pos);
            sp_wanfa.setAnchorPoint(0, 0);
            this.addChild(sp_wanfa);

            var scale9sprite = new cc.Scale9Sprite(res.sp_picback_png, cc.rect(0, 0, 1, 1), cc.rect(0.25, 0.25, 0.5, 0.5));
            scale9sprite.setName('s9p');
            scale9sprite.setAnchorPoint(0, 1);

            var maxLength = 0;
            var textHeight = 0;
            var fontSize = 25;
            var marginSize = cc.p(11, 5);
            var fontColor = cc.color(254, 245, 92);
            var scale9Height = 0;
            var scale9Width = 0;
            for (var i = 0; i < arr.length; i++) {
                var text = new ccui.Text();
                text.setFontSize(fontSize);
                text.setColor(fontColor);
                text.setAnchorPoint(0, 0);
                text.setString(arr[i]);
                text.setName('text' + i);
                var twidth = text.getVirtualRendererSize().width;
                textHeight = text.getAutoRenderSize().height;
                if (!scale9Height)
                    scale9Height = Math.max(arr.length * (textHeight + marginSize.y) + 3 * marginSize.y, sp_wanfa_size.height);
                text.setPosition(marginSize.x, scale9Height - marginSize.y - (textHeight + marginSize.y) * (i + 1));
                text.setTextVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER);
                scale9sprite.addChild(text);
                maxLength = twidth > maxLength
                    ? twidth
                    : maxLength;
            }

            scale9Width = maxLength + marginSize.x * 2;
            scale9sprite.setPosition(-scale9Width, sp_wanfa_size.height);
            scale9sprite.setPreferredSize(cc.size(scale9Width, scale9Height));
            sp_wanfa.addChild(scale9sprite);

            var pullOrPush = true;
            TouchUtil.setOnclickListener(sp_wanfa, function () {
                //console.log(sp_wanfa.getChildrenCount());
                sp_wanfa.stopAllActions();
                if (pullOrPush)
                    sp_wanfa.runAction(cc.moveTo(0.25, sp_wanfa_Pos.x + scale9Width, sp_wanfa_Pos.y));
                else
                    sp_wanfa.runAction(cc.moveTo(0.25, sp_wanfa_Pos));
                pullOrPush = !pullOrPush;
            });
        },
        showArrow: function (pai, row) {
            this.hideArrow();
            var arrow = pai.getParent().getChildByName('arrow');
            if (!arrow) {
                arrow = new cc.Sprite(res.arrow);
                arrow.setAnchorPoint(0.5, 0);
                arrow.setName('arrow');
                arrow.setLocalZOrder(100);
                pai.getParent().addChild(arrow);
                var duration = 0.8;
                arrow.setOpacity(168);
            }
            arrow.setVisible(true);
            arrow.setPositionX(pai.getPositionX());
            arrow.setPositionY(pai.getPositionY() + 10);
            arrow.runAction(cc.sequence(cc.spawn(cc.moveBy(duration, 0, +16), cc.fadeTo(duration, 255))
                , cc.spawn(cc.moveBy(duration, 0, -16), cc.fadeTo(duration, 168))).repeatForever());
        },
        showTip: function (content, isShake) {
            isShake = _.isUndefined(isShake)
                ? true
                : isShake;
            var scale9sprite = $('top_tip');
            if (!(scale9sprite instanceof cc.Scale9Sprite)) {
                var newScale9sprite = new cc.Scale9Sprite(majiang_gs.res.round_rect_91_png_mj, cc.rect(0, 0, 91, 32), cc.rect(46, 16, 1, 1));
                newScale9sprite.setName('top_tip');
                scale9sprite.setAnchorPoint(0.5, 0.5);
                newScale9sprite.setPosition(scale9sprite.getPosition());
                scale9sprite.getParent().addChild(newScale9sprite);
                var lb = $('top_tip.lb_tip');

                text = new ccui.Text();
                text.setName('lb_tip');
                text.setFontSize(lb.getFontSize());
                text.setTextColor(lb.getTextColor());
                text.enableOutline(cc.color(38, 38, 38), 1);
                newScale9sprite.addChild(text);

                lb.removeFromParent(true);
                scale9sprite.removeFromParent(true);
                scale9sprite = newScale9sprite;
            }
            var text = $('top_tip.lb_tip');
            text.setString(content);
            var size = cc.size(text.getVirtualRendererSize().width + 35, scale9sprite.getContentSize().height);
            text.setPosition((text.getVirtualRendererSize().width + 35) / 2, scale9sprite.getContentSize().height / 2);
            scale9sprite.setContentSize(size);
            scale9sprite.setScale(1.2);
            scale9sprite.setVisible(true);
            if (isShake)
                scale9sprite.runAction(cc.sequence(cc.scaleTo(0.2, 1.4), cc.scaleTo(0.2, 1.2)));
        },
        hideTip: function () {
            if (!isReplay)
                $('top_tip').setVisible(false);
        },
        hideArrow: function () {
            for (var i = 0; i < 4; i++) {
                var arrow = $('row' + i + '.c0.arrow');
                if (arrow)
                    arrow.removeFromParent(true);
            }
        },
        showChiLayer: function (paiId, cb) {
            var that = this;
            // var paiArr = paiArrBak[row] || that.getPaiArr();
            var paiArr = that.getPaiArr();
            paiArr.push(paiId);
            var arr = [
                [paiId - 2, paiId - 1, paiId],
                [paiId - 1, paiId, paiId + 1],
                [paiId, paiId + 1, paiId + 2]
            ];
            var posibleIdxArr = [];
            for (var i = 0; i < arr.length; i++) {
                var a = arr[i][0];
                var b = arr[i][1];
                var c = arr[i][2];
                if (isSameColor(a, b) && isSameColor(a, c) &&
                    paiArr.indexOf(a) >= 0 && paiArr.indexOf(b) >= 0 && paiArr.indexOf(c) >= 0)
                    posibleIdxArr.push(i);
            }
            if (posibleIdxArr.length == 1) {
                cb(arr[posibleIdxArr[0]][1], paiId);
                // that.sendChiPengGang(OP_CHI, 2, arr[posibleIdxArr[0]][1], paiId);
                that.hideChiPengGangHu();
            }
            else if (posibleIdxArr.length > 1) {
                var layer = that.chiLayer;
                if (!layer) {
                    var scene = ccs.load(majiang_gs.res.ChiPanel_json);
                    layer = scene.node;
                    layer.setName('chiLayer');
                    layer.retain();
                    that.chiLayer = layer;
                }
                that.addChild(layer);

                $('root.g0', layer).setVisible(posibleIdxArr.length >= 1);
                $('root.g1', layer).setVisible(posibleIdxArr.length >= 2);
                $('root.g2', layer).setVisible(posibleIdxArr.length >= 3);

                var fun = function (node) {
                    var parentName = node.getParent().getName();
                    var userData = $('root.' + parentName + '.' + 1, layer).getUserData();
                    var _paiId = userData.pai;
                    var paiId = userData.ori_pai_id;
                    cb(_paiId, paiId);
                    // that.sendChiPengGang(OP_CHI, 2, _paiId, paiId);
                    that.hideChiPengGangHu();
                    layer.removeFromParent(false);
                };

                for (var i = 0; i < posibleIdxArr.length; i++) {
                    for (var j = 0; j < 3; j++) {
                        var pai = $('root.g' + i + '.' + j, layer);
                        var _paiId = arr[posibleIdxArr[i]][j];
                        var paiName = getPaiNameByRowAndId(2, _paiId, true, false);
                        pai.setUserData({pai: _paiId, ori_pai_id: paiId});
                        setSpriteFrameByName(pai, paiName, majiang_gs.res.pai0plist);

                        TouchUtil.setOnclickListener(pai, fun);
                    }
                }

                TouchUtil.setOnclickListener($('root.btn_close', layer), function () {
                    layer.removeFromParent();
                });
                TouchUtil.setOnclickListener($('root', layer), function () {
                    // layer.removeFromParent();
                });
            }
        },
        playEffect: function (filename, sex) {
            playEffect(filename, sex);
        },
        setHuTipVisible: function (visible) {
            for (var i = 0; i < 14; i++) {
                var cardSprite = this.getPai(2, i);
                if (cardSprite.getChildByName('hucardSprite')) {
                    cardSprite.getChildByName('hucardSprite').stopAllActions();
                    cardSprite.getChildByName('hucardSprite').setVisible(visible);
                }
            }
        },
        showChangeScore: function (row, score) {
            if (!score) {
                return;
            }
            var txt = new cc.LabelBMFont(score > 0
                ? '+' + score
                : score, score < 0
                ? res.score_blue_fnt
                : res.score_yellow_fnt);
            var change_sroce_node = $('info' + row + '.change_sroce_node');
            change_sroce_node.addChild(txt);
            txt.runAction(
                cc.sequence(
                    cc.moveBy(1.5, cc.p(0, 30)),
                    cc.callFunc(function () {
                        txt.removeFromParent(true);
                    })
                )
            );
        },
        HuCardTip: function (showdata, posx, isVisible) {
            var hupaitip = this.getChildByName('hupaitip');
            if (!isVisible && hupaitip) {
                hupaitip.setVisible(isVisible);
                return;
            }
            if (showdata == null) {
                for (var i = 0; i < 14; i++) {
                    var pai = this.getPai(2, i);
                    var userData = pai.getUserData();
                    userData.hucards = null;
                }
                return;
            }
            var tiplength = showdata.length;
            if (hupaitip) {
                hupaitip.setVisible(true);
                hupaitip.setContentSize(cc.size(120 + 120 * tiplength, 80));
                //设置位置
                posx = posx + 40;
                if (posx + hupaitip.getContentSize().width / 2 > maLayer.getContentSize().width) {
                    posx = maLayer.getContentSize().width - hupaitip.getContentSize().width / 2 - 20;
                } else if (posx - hupaitip.getContentSize().width / 2 < 0) {
                    posx = hupaitip.getContentSize().width / 2 + 20;
                }
                hupaitip.setPositionX(posx);
                for (var i = 0; i < 9; i++) {
                    var card = hupaitip.getChildByName('card' + (i + 1));
                    var fantext = hupaitip.getChildByName('fantext' + (i + 1));
                    var fannum = hupaitip.getChildByName('fannum' + (i + 1));
                    var zhangtext = hupaitip.getChildByName('zhangtext' + (i + 1));
                    var zhangnum = hupaitip.getChildByName('zhangnum' + (i + 1));
                    if (tiplength > i) {
                        //card
                        card.setVisible(true);
                        var paiName = getPaiNameByRowAndId(2, showdata[i][0], true, true);
                        setSpriteFrameByName(card, paiName, majiang_gs.res.pai0plist);
                        card.setPosition(cc.p(-5 + 120 * (i + 1), hupaitip.getContentSize().height / 2));
                        fantext.setVisible(true);
                        fantext.setPosition(cc.p(60 + 120 * (i + 1), 60));
                        fannum.setVisible(true);
                        fannum.setPosition(cc.p(40 + 120 * (i + 1), 60));
                        fannum.setString(showdata[i][1]);
                        zhangtext.setVisible(true);
                        zhangtext.setPosition(cc.p(60 + 120 * (i + 1), 20));
                        zhangnum.setVisible(true);
                        zhangnum.setString(showdata[i][2]);
                        zhangnum.setPosition(cc.p(40 + 120 * (i + 1), 20));
                    } else {
                        card.setVisible(false);
                        fantext.setVisible(false);
                        fannum.setVisible(false);
                        zhangtext.setVisible(false);
                        zhangnum.setVisible(false);
                    }
                }
            } else {
                var hupaitip = new cc.Scale9Sprite(res.toast_bg_png, null, cc.rect(10, 10, 10, 10));
                hupaitip.setName('hupaitip');
                hupaitip.setAnchorPoint(cc.p(0.5, 0));
                hupaitip.setContentSize(cc.size(120 + 120 * tiplength, 80));
                hupaitip.setPosition(cc.p(maLayer.getContentSize().width - 20, 172));
                maLayer.addChild(hupaitip);
                //设置位置
                posx = posx + 40;
                if (posx + hupaitip.getContentSize().width / 2 > maLayer.getContentSize().width) {
                    posx = maLayer.getContentSize().width - hupaitip.getContentSize().width / 2 - 20;
                } else if (posx - hupaitip.getContentSize().width / 2 < 0) {
                    posx = hupaitip.getContentSize().width / 2 + 20;
                }
                hupaitip.setPositionX(posx);

                var huSprite = new cc.Sprite(res.hupaitip_hu);
                huSprite.setPosition(cc.p(40, hupaitip.getContentSize().height / 2));
                hupaitip.addChild(huSprite);
                for (var i = 0; i < 9; i++) {
                    //card
                    var card = new cc.Sprite();
                    card.setScale(0.88);
                    card.setName('card' + (i + 1));
                    card.setPosition(cc.p(-5 + 120 * (i + 1), hupaitip.getContentSize().height / 2));
                    hupaitip.addChild(card);

                    var fantext = new ccui.Text();
                    fantext.setString('番');
                    fantext.setName('fantext' + (i + 1));
                    fantext.setFontSize(20);
                    fantext.setTextColor(cc.color(0, 255, 0));
                    fantext.enableOutline(cc.color(38, 38, 38), 1);
                    fantext.setPosition(cc.p(60 + 120 * (i + 1), 60));
                    hupaitip.addChild(fantext);
                    var fannum = new ccui.Text();
                    fannum.setName('fannum' + (i + 1));
                    fannum.setFontSize(20);
                    fannum.setTextColor(cc.color(255, 255, 0));
                    fannum.enableOutline(cc.color(38, 38, 38), 1);
                    fannum.setPosition(cc.p(40 + 120 * (i + 1), 60));
                    hupaitip.addChild(fannum);
                    var zhangtext = new ccui.Text();
                    zhangtext.setString('张');
                    zhangtext.setName('zhangtext' + (i + 1));
                    zhangtext.setFontSize(20);
                    zhangtext.setTextColor(cc.color(0, 255, 0));
                    zhangtext.enableOutline(cc.color(38, 38, 38), 1);
                    zhangtext.setPosition(cc.p(60 + 120 * (i + 1), 20));
                    hupaitip.addChild(zhangtext);
                    var zhangnum = new ccui.Text();
                    zhangnum.setName('zhangnum' + (i + 1));
                    zhangnum.setFontSize(20);
                    zhangnum.setTextColor(cc.color(255, 255, 0));
                    zhangnum.enableOutline(cc.color(38, 38, 38), 1);
                    zhangnum.setPosition(cc.p(40 + 120 * (i + 1), 20));
                    hupaitip.addChild(zhangnum);
                    if (tiplength > i) {
                        card.setVisible(true);
                        var paiName = getPaiNameByRowAndId(2, showdata[i][0], true, true);
                        setSpriteFrameByName(card, paiName, majiang_gs.res.pai0plist);
                        fantext.setVisible(true);
                        fannum.setVisible(true);
                        fannum.setString(showdata[i][1]);
                        zhangtext.setVisible(true);
                        zhangnum.setVisible(true);
                        zhangnum.setString(showdata[i][2]);
                    } else {
                        card.setVisible(false);
                        fantext.setVisible(false);
                        fannum.setVisible(false);
                        zhangtext.setVisible(false);
                        zhangnum.setVisible(false);
                    }
                }
            }
        },
        sortPaiArr: function (paiArr, row, huPaiId) {
            var _paiArr = deepCopy(paiArr);
            if (row == 2)
                _.pull(_paiArr, 0);
            _paiArr.sort(compareTwoNumbers);


            return _paiArr;
        },
        changeBtnStatus: function () {
            $('btn_bg').setVisible(!$('btn_bg').isVisible());
            $('setting').setVisible(!$('setting').isVisible());
            $('btn_changeTable').setVisible(!$('btn_changeTable').isVisible());
            $('location_btn_red').setVisible(!$('location_btn_red').isVisible());
            // var isVisible = $('chat').isVisible();
            // $('chat').setVisible(!$('chat').isVisible());
            $('jiesan').setVisible(!$('jiesan').isVisible());
            $('btn_control_btns').setFlippedY(!$('btn_control_btns').isFlippedY());
        },
        hideControlBtns: function () {
            $('btn_bg').setVisible(false);
            $('setting').setVisible(false);
            // $('chat').setVisible(false);
            $('jiesan').setVisible(false);
            $('btn_changeTable').setVisible(false);
            $('location_btn_red').setVisible(false);
            $('btn_control_btns').setFlippedY(true);
        },

        getRowByUid: function (uid) {
            return uid2position[uid];
        },
        getOriginalPos: function () {
            return 2;
        },
        /**
         * 胡牌按钮特殊处理
         * @private
         * */
        _handleSpeacilHu: function (pai_id) {
            var self = this;
            console.log('胡牌按钮特殊处理【胡类型】' + this._huType + '牌：' + pai_id);
            var cpghg = $('cpghg');
            var hu = cpghg.getChildByName('hu');
            var hu_wang = cpghg.getChildByName('hu_wang');
            if (this._huType === majiang.Hu.ZiMo) {
                hu.setVisible(true);
                if (cc.sys.isObjectValid(hu_wang)) {
                    hu_wang.removeFromParent(true);
                }
                return;
            }
            network.stop();
            // 特么摸得牌暂时不显示
            safeHide(hu);
            if (!cc.sys.isObjectValid(hu_wang)) {
                hu_wang = new cc.Sprite(majiang_gs.res.btn_wangdiao);
                hu_wang.setName('hu_wang');
                cpghg.addChild(hu_wang);
            }
            hu_wang.x = hu.x;
            hu_wang.y = hu.y;
            TouchUtil.removeListeners(hu_wang);
            TouchUtil.setOnclickListener(hu_wang, function () {
                network.start();
                self.sendChiPengGang(OP_HU, 2, pai_id);
                self.hideChiPengGangHu();
            });
        },

        /**
         * 吃碰杠胡听
         * @param {Object} data
         * @private
         * */
        _onChiPengGangHuTing: function (data) {
            data = data || g_last_net_data[4005];
            g_last_net_data[4005] = data;

            this._hideReady();
            this._refreshRoundAndPai();
            this._huType = majiang.Hu.ZiMo;
            var self = this;

            var setCards = function (target, card_arr) {
                var childs = target.getChildren();
                for (var m = 0; m < childs.length; m++) {
                    safeHide($('' + m, target));
                }

                var card_count = card_arr.length;
                for (var i = 0; i < card_count; i++) {
                    var card = $('' + i, target);
                    var pos = $('n', target).getPosition();
                    if (!card) {
                        card = duplicateNode($('row2.c0.b0'));
                        card.setName('' + i);
                        card.setPosition(cc.p(pos.x + i * 70, pos.y));
                        target.addChild(card);
                    }
                    card.pai_id = card_arr[i];
                    card.setVisible(true);
                    var name = getPaiNameByRowAndId(2, card_arr[i], true);
                    setSpriteFrameByName(card, name, majiang_gs.res.pai0plist);
                    card.setUserData({paiId: card_arr[i]});
                }

                var offset_x = 0;
                var bg = $('bg', target);
                var contentSize = bg.getContentSize();
                if (card_count > 1) {
                    offset_x = 65 * (card_count - 1);
                    contentSize.width = 108 + offset_x;
                    bg.setContentSize(contentSize);
                } else {
                    contentSize.width = 108;
                    bg.setContentSize(contentSize);
                }
                bg.setVisible(true);
                return offset_x;
            };

            // 操作对象
            var OpType = {
                Chi: 0,
                Peng: 1,
                Gang: 2,
                Hu: 3,
                Ting: 4
            };
            var op_map = {};
            for (var key in OpType) {
                if (OpType.hasOwnProperty(key)) {
                    op_map[OpType[key]] = [];
                }
            }
            var tishi = data['tishi'];
            for (var index = 0; index < tishi.length; index++) {
                var pai_id = tishi[index]['pai_id'];
                var op = tishi[index]['op'] || [false, false, false, false, false];
                for (var op_idx = 0; op_idx < op.length; op_idx++) {
                    if (op[op_idx]) {
                        op_map[op_idx].push(pai_id);
                    }
                }
                if (tishi[index]['huType']) {
                    this._huType = tishi[index]['huType'];
                }
            }
            cc.log('op_map ==== ', op_map);
            if (!isReplay  ||  true) {
                var cpghg = $('cpghg');
                var chi = $('cpghg.chi');
                var peng = $('cpghg.peng');
                var gang = $('cpghg.gang');
                var hu = $('cpghg.hu');
                var ting = $('cpghg.ting');
                var guo = $('cpghg.guo');
                if(!isReplay ){
                    safeShow(cpghg);
                }
                safeHide(chi);
                safeHide(peng);
                safeHide(gang);
                safeHide(hu);
                safeHide(ting);
                safeHide(guo);



                var show_arr = [];    // 王钓时点过显示的节点
                var node_arr = [];    // 操作节点数组
                var op_arr = [];      // 可操作的数组
                var node_offset = []; // 操作节点偏移量
                var pai_id = -1;
                if (op_map[OpType.Chi].length > 0) {
                    node_arr.push(chi);
                    op_arr.push(OP_CHI);
                    pai_id = op_map[OpType.Chi][0];
                    TouchUtil.setOnclickListener(chi, function () {
                        self.showChiLayer(pai_id, function (paiId, oriPaiId) {
                            self.sendChiPengGang(OP_CHI, 2, paiId, oriPaiId);
                        });
                    });
                    node_offset.push(setCards(chi, op_map[OpType.Chi]));
                }
                if (op_map[OpType.Peng].length > 0) {
                    node_arr.push(peng);
                    op_arr.push(OP_PENG);
                    pai_id = op_map[OpType.Peng][0];
                    TouchUtil.setOnclickListener($('cpghg.peng'), function () {
                        self.sendChiPengGang(OP_PENG, 2, pai_id);
                        self.hideChiPengGangHu();
                    });
                    node_offset.push(setCards(peng, op_map[OpType.Peng]));
                    show_arr.push(peng);
                }
                if (op_map[OpType.Gang].length > 0) {
                    node_arr.push(gang);
                    op_arr.push(OP_GANG);
                    var card_arr = op_map[OpType.Gang] || [];
                    node_offset.push(setCards(gang, card_arr));
                    TouchUtil.removeListeners(gang);
                    if (card_arr.length > 1) {
                        for (var idx = 0; idx < card_arr.length; idx++) {
                            (function (idx) {
                                var pai = $('' + idx, gang);
                                TouchUtil.removeListeners(pai);
                                TouchUtil.setOnclickListener(pai, function () {
                                    self.sendChiPengGang(OP_GANG, 2, pai.pai_id);
                                    self.hideChiPengGangHu();
                                });
                            })(idx);
                        }
                    } else {
                        TouchUtil.setOnclickListener(gang, function () {
                            self.sendChiPengGang(OP_GANG, 2, card_arr[0]);
                            self.hideChiPengGangHu();
                        });
                    }
                    show_arr.push(gang);
                }
                if (op_map[OpType.Hu].length > 0) {
                    node_arr.push(hu);
                    op_arr.push(OP_HU);
                    pai_id = op_map[OpType.Hu][0];
                    TouchUtil.setOnclickListener(hu, function () {
                        network.start();
                        self.sendChiPengGang(OP_HU, 2, pai_id);
                        self.hideChiPengGangHu();
                    });
                    node_offset.push(setCards(hu, op_map[OpType.Hu]));
                }
                if (op_map[OpType.Ting].length > 0) {
                    node_arr.push(ting);
                    op_arr.push(OP_TING);
                    node_offset.push(100);
                    pai_id = op_map[OpType.Ting][0];
                    cpghg.setTouchEnabled(false);
                    TouchUtil.setOnclickListener(ting, function () {
                        network.start();

                        if (gameData.mapId == app.map_id.GanSu_BaiJiao) {
                            self.sendChiPengGang(OP_TING, 2, pai_id);
                            // baijiaoStep = 1;
                            // self.showBaijiao();
                        } else if ((gameData.mapId == app.map_id.GanSu_KaErTiao)) {
                            tiantingOpt = true;
                        }
                        if(gameData.huTipData){
                            var tishiArr = data.tishi;
                            var tishiObj ={};
                            for(var ti in tishiArr){
                                var tarr = gameData.huTipData.tishi[tishiArr[ti].pai_id + ''];
                                tishiObj[tishiArr[ti].pai_id + ''] = tarr;
                            }
                            gameData.huTipData.tishi = tishiObj;
                        }
                        self.showTishiTip(gameData.huTipData);
                        self.tingOperatePais();
                        self.hideChiPengGangHu();
                    });
                }else{
                    cpghg.setTouchEnabled(true);
                }
                node_arr.push(guo);

                TouchUtil.setOnclickListener(guo, function () {
                    if (self._huType !== 0 && network.isStoped()) {
                        for (var show_idx = 0; show_idx < show_arr.length; show_idx++) {
                            safeShow(show_arr[show_idx]);
                        }
                        network.start();
                        return;
                    }
                    if (op_map[OpType.Hu].length > 0 && self.isMyTurn()) {
                        // showMessageBox('您当前可以自摸, 确定要点【过】吗?', function () {
                        self.sendChiPengGang(OP_PASS, 2, pai_id);
                        self.hideChiPengGangHu();
                        // });
                    } else {
                        self.sendChiPengGang(OP_PASS, 2, pai_id);
                        self.hideChiPengGangHu();
                    }
                });

                // 位置适配
                index = 0;
                var node_count = node_arr.length;
                var total_offset_x = 0;
                for (; index < node_arr.length; index++) {
                    safeShow(node_arr[index]);
                    node_arr[index].setPositionX(posConf.cpghgPositionX[node_count][index] + total_offset_x);
                    total_offset_x += node_offset[index];
                }
                this.countDown(12);

                // 胡牌按钮特殊处理
                var hu_wang = cpghg.getChildByName('hu_wang');
                if (cc.sys.isObjectValid(hu_wang)) {
                    hu_wang.removeFromParent(true);
                }
                if (op_map[OpType.Hu].length > 0) {
                    this._handleSpeacilHu(op_map[OpType.Hu][0]);
                    if (this._huType !== majiang.Hu.ZiMo) {
                        for (var show_idx = 0; show_idx < show_arr.length; show_idx++) {
                            safeHide(show_arr[show_idx]);
                        }
                    }
                }
                if(isReplay){
                    var  row = uid2position[data.uid]
                    var paiId = pai_id ;
                    var cpg = $('cpghRep' + row);
                    for (var i = 0; i < 7; i++) {
                        if (!cpg.getChildByName('sp1_' + i)) {
                            var sp = new cc.Sprite(res['sp1_' + i]);
                            sp.setPosition(cpg.getChildByName('sp_' + i).getPosition());
                            sp.setName('sp1_' + i);
                            cpg.addChild(sp);
                            sp.setVisible(false);
                        }
                    }
                    var  chi  = op_map[OpType.Chi].length > 0 ?true :false;
                    var  peng  = op_map[OpType.Peng].length > 0 ?true :false;
                    var  gang  = op_map[OpType.Gang].length > 0 ?true :false;
                    var  hu  = op_map[OpType.Hu].length > 0 ?true :false;
                    var  bai  = op_map[OpType.Ting].length > 0 ?true :false;
                    $('cpghRep' + row + '.sp1_0').setVisible(chi);
                    $('cpghRep' + row + '.sp1_1').setVisible(peng);
                    $('cpghRep' + row + '.sp1_2').setVisible(gang);
                    $('cpghRep' + row + '.sp1_3').setVisible(hu);
                    $('cpghRep' + row + '.sp1_4').setVisible(true);
                    $('cpghRep' + row + '.sp1_5').setVisible(false);
                    $('cpghRep' + row + '.sp1_6').setVisible(bai);

                    $('cpghRep' + row + '.sp_0').setVisible(!chi);
                    $('cpghRep' + row + '.sp_1').setVisible(!peng);
                    $('cpghRep' + row + '.sp_2').setVisible(!gang);
                    $('cpghRep' + row + '.sp_3').setVisible(!hu);
                    $('cpghRep' + row + '.sp_4').setVisible(false);
                    $('cpghRep' + row + '.sp_5').setVisible(true);
                    $('cpghRep' + row + '.sp_6').setVisible(!bai);

                    var pai = $('cpghRep' + row + '.sp_pai');
                    var paiName = getPaiNameByRowAndId(2, paiId, true);
                    pai.setScale(0.65, 0.65);
                    setSpriteFrameByName(pai, paiName, majiang_gs.res.pai0plist);
                    cpg.setVisible(true);
                }
            }
        },
        //获取自己的ChatInfo节点
        getChatInfoNode: function (idx) {
            var self = this;
            var ChatInfoNode = null;
            if ($('info' + idx)) {
                ChatInfoNode = $('info' + idx + '.ChatInfo');
            }
            return ChatInfoNode;
        },
        //获取道具投放坐标
        getEffectEmojiPos: function (caster, patient, isNotMid) {
            var self = this;
            var pos = {};
            var infoCasterHead = $('info' + caster + '.head');
            var infoPatientHead = $('info' + patient + '.head');
            pos[caster] = infoCasterHead ? infoCasterHead.getParent().convertToWorldSpace(infoCasterHead.getPosition()) : cc.p(cc.winSize.width / 2, cc.winSize.height / 2);
            pos[patient] = (patient != self.getOriginalPos() && infoPatientHead) || isNotMid ? infoPatientHead.getParent().convertToWorldSpace(infoPatientHead.getPosition()) : cc.p(cc.winSize.width / 2, cc.winSize.height / 2);
            return pos;
        },
    });
    exports.MaLayer_lnbj.getPaiNameByRowAndId = getPaiNameByRowAndId;


    var recoverColor = function (sprite) {
        sprite.setColor(cc.color(255, 255, 255));
    };

    //判断两个数组是否相同
    var Equals = function (object1, object2) {
        for (var propName in object1) {
            if (object1.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
                return false;
            }
            else if (typeof object1[propName] != typeof object2[propName]) {
                //Different types => not equal
                return false;
            }
        }
        for (var propName in object2) {
            if (object1.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
                return false;
            }
            else if (typeof object1[propName] != typeof object2[propName]) {
                return false;
            }
            if (!object1.hasOwnProperty(propName))
                continue;
            if (object1[propName] instanceof Array && object2[propName] instanceof Array) {
                if (!Equals(object1[propName], object2[propName]))
                    return false;
            } else if (object1[propName] instanceof Object && object2[propName] instanceof Object) {
                if (!Equals(object1[propName], object2[propName]))
                    return false;
            } else if (object1[propName] != object2[propName]) {
                return false;
            }
        }
        return true;
    };
    /**
     * 删除数组中的项
     * @param list
     * @param obj
     */
    var removeObjArray = function (list, obj) {
        if (list == null) return;
        var pos = -1;
        for (var i = 0; i < list.length; i++) {
            if (list[i] == obj) {
                pos = i;
                break;
            }
        }
        if (pos >= 0) {
            list.splice(pos, 1);
        }
        return list;
    };

})(window);
